Here is my situation. I have two arduino boards a Uno (slave) Mega (master) connected via I2C. I need to send two different variables from the slave to the master. My problem is that when the slave sends the variables the master only receives the second variable. How can I send two different variables over I2C? Here is my current code:
//i2c Master(MEGA)
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
int reading = 0;
int x;
int y;
Wire.beginTransmission(5); // Transmit to device #5
Wire.write(byte(0x02));
Wire.endTransmission();
// Request reading from sensor
Wire.requestFrom(5,1);
//if(1<= Wire.available()) //If 1 byte was recieved
x = Wire.read();
Serial.println(x);
delay(250);
Wire.beginTransmission(5); // Transmit to device #5
Wire.write(byte(0x10));
Wire.endTransmission();
// Request reading from sensor
Wire.requestFrom(5,1);
//if(1<= Wire.available()) //If 1 byte was recieved
y = Wire.read();
Serial.println(y);
delay(250);
}
/*
while(Wire.available())
{
int x = Wire.read();
Serial.print(x);
int y = Wire.read();
}
}
*/
void loop()
{
}
/*
*I2C_Slave (UNO)
*Monitors I2C requests and echoes these to the serial port
*/
#include <Wire.h>
int x;
int y;
int c;
const int address = 5; // The address to be used by the communicating devices
void setup()
{
Wire.begin(address); // Join I2C bus using this address
Wire.onRequest(requestEvent); // Register event to handle requests
Wire.onReceive(receiveEvent);
x = 5;
y = 9;
}
void loop()
{
delay(100);// Nothing here, all the work is done in receiveEvent
}
void receiveEvent(int howMany)
{
while(Wire.available()>0)
{
int c = Wire.read();
}
}
void requestEvent()
{
if(c = byte(0x02))
{
Wire.write(x);
}
delay(250);
if(c = byte(0x10))
{
Wire.write(y);
}
}
When I run the two codes below my x variable gets over written with the y variable, so then I only get a y y when it is printed out on the serial monitor.