I am connecting 2 Arduino UNO but there is no response. First I upload the program on the master and then on the slave. While the 2 arduino are connected on my laptop I write on the Serial monitor ‘H’ or ‘L’ but nothing happens.
Ioannis Demetriades, if you change something to your sketch, please show both the Master and Slave sketches to us. So we can see for ourselves that you have fixed the '==' and registered the receive event.
The OP has to place == operator in three places: 2 places in Master Codes and 1 place in Slave Codes.
The OP has to write 'L' in place of 'H' in one place of the Master Code.
I don't see, in the receiver setup, where you register the receive event. See the slave reader example.
In TWI Protocol, when a valid data is present in the TWI Receiver (TWDR Register), the MCU is automatically interrupted and the Wire.onReceive(InterruptHandler) message/event is triggered, which in turn calls upon the user-defined subroutine (the ISR). Therefore, the user is required to declare this Interrupthandler in the setup of the Slave Codes in this way: Wire.onReceive(receiveEvent);.
I revised your code and it works on my two Unos. This code has been tested so if it does not work for you, then there is a hardware problem. I used no pullups. The Wire library enables the internal pullups. That, sometimes, is enough pullup, but not always.
See comments for the changes. Note the = in the if statements has been changed to ==.
Master code
#include<Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop() {
while (Serial.available())
{
char c = Serial.read();
Serial.println(c);
if (c == 'H') // = for assignment == for compare
{
Serial.println("send H");
Wire.beginTransmission(5);
Wire.write('H');
Wire.endTransmission();
}
else if (c == 'L') // = for assignment == for compare
{
Serial.println("send L");
Wire.beginTransmission(5);
Wire.write('L'); // had send 'H'
Wire.endTransmission();
}
}
}
Slave code
#include<Wire.h>
char c;
const byte led = 13; // change to suit (was 8)
void setup()
{
Wire.begin(5);
Wire.onReceive(receiveEvent); // register rcv event
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop()
{
}
void receiveEvent(int howMany)
{
while (Wire.available())
{
c = Wire.read(); // made c global
if (c == 'H') // = for assign == for compare
digitalWrite(led, HIGH);
else
digitalWrite(led, LOW);
}
//Serial.print(" rcv event ");
//Serial.println(c);
}
You should avoid using i2c addresses below 8 as they are reserved for special functions.
While I think many of them work on AVR, some MCUs will have issues with this.
Thanks the program now run but when i use a different pin for the LED it doesnt. Also, shouldnt i use the Serial port of the master to communicate. When i do the built in LED of the slave doesnt work unless i use the Serial Monitor of the slave.