Skip to content

Instantly share code, notes, and snippets.

@spitty
Created November 13, 2016 11:50
Show Gist options
  • Save spitty/b30bdc3144bdff43c77eedc63efa673e to your computer and use it in GitHub Desktop.
Save spitty/b30bdc3144bdff43c77eedc63efa673e to your computer and use it in GitHub Desktop.
// Original: https://oscarliang.com/raspberry-pi-arduino-connected-i2c/
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600); // start serial for output
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.println("Ready!");
}
void loop() {
delay(100);
}
// callback for received data
void receiveData(int byteCount) {
while (Wire.available()) {
number = Wire.read();
Serial.print("data received: ");
Serial.println(number);
if (number == 1) {
if (state == 0) {
digitalWrite(13, HIGH); // set the LED on
state = 1;
}
else {
digitalWrite(13, LOW); // set the LED off
state = 0;
}
}
}
}
// callback for sending data
void sendData() {
Wire.write(number);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment