Skip to content

Instantly share code, notes, and snippets.

@dotdoom
Created June 1, 2016 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dotdoom/9ee7c65791e59fd421cf199a752d6701 to your computer and use it in GitHub Desktop.
Save dotdoom/9ee7c65791e59fd421cf199a752d6701 to your computer and use it in GitHub Desktop.
An example of doing an i2c slave with Arduino
#define I2CAddress 0x42
void setup() {
Wire.begin(I2CAddress);
// Remember to keep those handlers as time-critical as possible:
// no interrupts will be happening while these are running.
// Also the other end of i2c communication might just
// give up waiting. So keep the logic in loop() and let i2c
// handlers only operate on ready data.
Wire.onReceive(i2cReceive);
Wire.onRequest(i2cRequest);
}
volatile byte i2cRegister = 0xff;
void i2cReceive(int bytesReceived) {
i2cRegister = Wire.read();
if (bytesReceived > 1) {
// This is i2c "write" request; read data with Wire.read()...
}
// onReceive will not be invoked unless rxBuffer is empty.
// Clean it up manually.
while (Wire.available()) { Wire.read(); }
}
void i2cRequest() {
// Use Wire.write() to send the data from register i2cRegister...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment