i want to communicate between two arduinos i.e. arduino mega & nano. the mega is master and nano is slave. i need to send integer value from arduino mega to arduino nano via I2C communication (wire.h).
i am sending 300 & 400 values & i am getting 144 & 44 instead of 300 & 400. how can i achive this! please help me.
slave.ino (524 Bytes)
master.ino (283 Bytes)
Please read How to use this forum - please read. - Installation & Troubleshooting - Arduino Forum, specifically point#7 about posting code; your code is small enough and you will reach a bigger audience that can advice. Cell phone users usually can't read ino attachments.
@OP
1. Note the changes/comments that I have made/added in the Master Codes
#include<Wire.h>
void setup()
{
Wire.begin();//;
Serial.begin(9600);
}
void loop()
{
int a = 300; //0x012C
int b = 400; //0x0190
Wire.beginTransmission(0x40); //slaveAddress
Wire.write(highByte(a)); //I2C is byte oriented; write(a);
Wire.write(lowByte(a));
Wire.write(highByte(b)); //I2C is byte oriented; write(a);
Wire.write(lowByte(b));
Wire.endTransmission();
//delay(1000);
//int b = 400; //
//Wire.beginTransmission(0x40);
//Wire.write(b);
//Wire.endTransmission();
delay(1000);
}
2. Note the changes/comments that I have made/added in the Slave Codes
#include<Wire.h>
#define led 13
volatile byte x1, x2, x3, x4;
volatile int y1, y2;
bool flag1 = false;
void setup()
{
Wire.begin(0x40);
Serial.begin(9600);
Wire.onReceive(receiveEvent);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop()
{
if (flag1 == true)
{
Serial.print("Recived a: ");
Serial.println(y1, DEC); //Serial Monitor shows: 300
//-------------------------
Serial.print("Recived b: ");
Serial.println(y2, DEC);
//-------------------------
flag1 = false; //reday for next cycle
}
}
void receiveEvent(int howMany)
{
x1 = Wire.read(); //x1 hilds upper byte of received a
x2 = Wire.read(); //x2 holds lower byte of received a
y1 = (int)x1 << 8 | (int)x2;
//------------------------
x3 = Wire.read(); //x1 hilds upper byte of received b
x4 = Wire.read(); //x2 holds lower byte of received b
y2 = (int)x3 << 8 | (int)x4;
//---------------------------
flag1 = true; //to indicate recevieEvent() handler is visited; do all print in loop()
}
/*
hile (Wire.available())
{
Serial.print("Data received ");
int R = Wire.read();
Serial.println(R);
Serial.println();
if (R == 300)
{
digitalWrite(13, LOW);
delay(1000);
}
else if (R == 400)
{
digitalWrite(13, HIGH);
delay(1000);
}
}
}
*/
3. Upload the sketch in both Master and Slave. Please, report the results.