0
votes

I'm trying to do serial communication between two Arduinos.

I used this circuit diagram and this code works perfectly;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    switch(Serial.read())
    { case 'A':
      digitalWrite(13,HIGH);
      break;
      case 'B':
      digitalWrite(13,LOW);
      break;
    }
}
}

But I don't want to use switch-case. I want to use if conditions. I'm trying this code;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    if(Serial.read()=='A')
    {
      digitalWrite(13,HIGH);
    }
    else if(Serial.read()=='B')
    {
      digitalWrite(13,LOW);
    }
}
}

But it doesn't work. My question is; why is works with switch-case but not with if conditions. Where is my fault? Can you fix it?

Thanks.

1

1 Answers

1
votes

I've tried both codes and I think that the problem is data reading. Here follows my test codes. Sender code:

void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println("A"),
  delay(1000);
  Serial.println("B"),
  delay(1000);
}

Receiver code:

int data;
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
if (Serial.available()) {
    data = Serial.read();
    if(data=='A')
    {
      digitalWrite(13,HIGH);
    }
    else if(data=='B')
    {
      digitalWrite(13,LOW);
    }
  }
}

When you try to test data read from serial communication it's always a good practice to save the buffer to a variable and then do all the control stuff. This way you can trust that the data is always the same. Here a more rigid explanation. When you do an if statement like the one that you've tested you don't actually test the same value in one loop.if(Serial.read()=='A') and else if(Serial.read()=='B') actually tests two different readings from the serial in two different times. When you do instead a single reading with data = Serial.read() and you compare the reading stored in a variable with expected value like data == 'A' the reading is done only one time and "remain the same" through all the loop. Note that the comparison it's done with char ('') not ("") in my test.

Hope I've helped solving your problem. Let us know it works for you