Hello, I try to make my Arduino react to specific command sended via I2C.
I was jus sending 2 different byte values - 79 and 80 - from the Raspberry for now and it worked. Example below:
#include <Wire.h>
#define SLAVE_ADDRESS 0x0a
int number = 0;
int state = 0;
void setup() {
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(12, HIGH); // set the LED on
digitalWrite(13, HIGH); // set the LED on
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop() {
delay(10);
}
// callback for received data
void receiveData(int byteCount){
while(Wire.available()) {
number = Wire.read();
if (number == 79)
{
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
}
if (number == 80){
digitalWrite(12, LOW);
digitalWrite(13, LOW);
}
}
}
// callback for sending data
void sendData(){
Wire.write(number);
}
but now I would want to use something different. I would like to react to same byte value (79) BUT with an additional parameter/argument - like (79, 0) and (79, 1). Code like:
if (number == 79, 1)
Any help?
I was looking in Wire.read() help but I couldn't find any useful info there.
#include <Wire.h>
void setup()
{
Wire.begin(4); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Serial.begin(57600); // start serial for output
}
void loop()
{
delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
Serial.print(F("howMany = ")); Serial.println(howMany);
Serial.print(F("available = ")); Serial.println(Wire.available());
byte number = Wire.read();
byte somethingElse = Wire.read();
Serial.print(F("number = ")); Serial.println(number);
Serial.print(F("somethingElse = ")); Serial.println(somethingElse);
Serial.println();
}
And the matching master sender that I used for testing the slave, based on the master writer example on the same page
#include <Wire.h>
void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
}
byte x = 0;
byte y = 79;
void loop()
{
Wire.beginTransmission(4); // transmit to device #4
Wire.write(y); // sends five bytes
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
x++;
if (x == 2)
{
x =0;
y++;
}
delay(2500);
}
I'm not an I2C specialist; there is no hardening and the code might not quite be as it's supposed to be. But it's a starting point.
Example output
...
...
howMany = 2
available = 2
number = 188
somethingElse = 0
howMany = 2
available = 2
number = 188
somethingElse = 1
howMany = 2
available = 2
number = 189
somethingElse = 0
howMany = 2
available = 2
number = 189
somethingElse = 1
...
...
Note: the code expects two bytes so your Pi needs to send two bytes.