I2C communication issue

Hello,
I would like to establish a 2way communication between 2 Arduino Uno.

Each Arduino can receive commands from the other.
On each Arduino there is a led and a button.

This is the code used on to make one way communication: the command is sent from Arduino A to Arduino B : when the button on Arduino A is pressed, the led on Arduino B is switched ON.

The code below works. The string "TEST" is correctly received on Arduino B. The problem is that the led on Arduino B goes on and off one time very quickly instead of remaining ON during 5 seconds. Same problem if I replace it with a buzzer.
I have tested with different Arduino's but same problem.

Does somebody has an idea ?
Thanks for your time.
Mario

Code on Arduino A

#include <Wire.h>
const int pldr = 3;  //  led
const int pbut = 4;  // button
int bs1 = 0;

void setup()
{
   Wire.begin(); 
   pinMode(pldr,OUTPUT); // led
   pinMode(pbut,INPUT);  // button
   Serial.begin(9600); 

}

void loop()
{
   bs1 = digitalRead(pbut); 
   if (bs1 == HIGH) {
      Wire.beginTransmission(4); 
      Wire.write("TEST"); 
      Serial.println("Command sent");      
      Wire.endTransmission();         
    }   
}

Code on Arduino B

#include <Wire.h>
const int pldr = 3;  // led
String readString;

void setup()
{
   Wire.begin(); 
   Wire.onReceive(receiveEvent); 
   pinMode(pldr,OUTPUT); // led
}

void loop()
{
}

void receiveEvent(int howMany)
{
  readString = "";
  while(Wire.available()){
       readString += (char)Wire.read();
       delay(200);
  }
  delay(200);
  if(readString == "TEST"){
     digitalWrite(pldr, HIGH);
     [b]delay(5000);[/b]
     digitalWrite(pldr, LOW);
     } 
}

the slave code needs to declare an address in the begin statement so that your master can find it.

Refer to this instructable

Also, in receiveEvent() you should set a variable to control the led which you then handle in the loop() instead of controlling the LED directly in receiveEvent() .
Something like:

testReceivedAtMs = millis() ;

And in the loop():

digitalWrite(pldr, (millis()-testReceivedAtMs < 5000) ? (HIGH) : (LOW) );

Hello
Thanks a lot for your responses.
It works ! :slight_smile:
This is the modified code.

void loop()
{       
    if ((da1 == 1) and (millis() - t1) > 2000) {
        digitalWrite(pldr, LOW); 
        da1 = 0;
     }  
}

void receiveEvent(int howMany)
{
  readString = "";
  while(Wire.available()){
     readString += (char)Wire.read();
     delay(200);
  }
  if(readString == "TEST"){
     Serial.println("Command received");
     digitalWrite(pldr, HIGH);
     da1 = 1;
     t1 = millis();
     } 
}