I'm having trouble trying to get my two Arduino Unos to communicate with each other over i2c. I'm trying to have the master request for analog values from the slave by sending a request to the slave device for one of the six ADC pin values.
Master Code
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(115200);
}
void loop()
{
Wire.beginTransmission(0x22); // Start communication with Arduino slave at address 0x22
for(byte i=0;i<4;i++)
{
Wire.write(i); // Request data from analog pin 'i'
delay(5); // Give the slave a moment to sample ADC and respond
while(Wire.available())
{
byte c = Wire.read();
Serial.println(c); // Print returned value to serial window
}
}
Wire.endTransmission(); // End communication with Arduino slave
delay(500);
}
Slave Code
#include <Wire.h>
void setup() {
Wire.begin(0x22);
Wire.onReceive(receivedHandler);
}
void loop() {
}
void receivedHandler() {
byte data = Wire.read();
byte analogValue;
if(data == 0) analogValue = analogRead(A0)>>2;
else if(data == 1) analogValue = analogRead(A1)>>2;
else if(data == 2) analogValue = analogRead(A2)>>2;
else if(data == 3) analogValue = analogRead(A3)>>2;
else analogValue = 0;
Wire.write(analogValue);
}
I can see that the data is being received by the slave, but the slave is not sending any data back, so I'm a bit confused how to send data back to the master. For the master there is "Wire.requestFrom(address, num of bytes)" to request a specific number of bytes, and for the slave "Wire.onRequest()" which will call a handler function to send back the number of bytes requested by the master, but for my application I won't be able to return more than 1 byte at a time.