Search code examples
arduinoled

Arduino LED blinking -> need some clarification and explanation


So, me and my friend were assigned a task: When 'A' is given as input to serial monitor, the led must blink once. When 'B' is given a input, the led must blink continuously. And we successfully finished the task using the code attached.

char a;
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  if(Serial.available())
  {
    a= Serial.read();
    if(a == 'A')
    {
      digitalWrite(13, HIGH);
      delay(1000); // Wait for 1000 millisecond(s)
      digitalWrite(13, LOW);
      delay(1000); // Wait for 1000 millisecond(s)
    }
  }

  if(a=='B')
  {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
  }
}

But then we have a doubt to be clarified. Both the conditions are given inside loop , but the one inside the if(Serial.available()) condition makes the led blink once while the condition outside the if(Serial.available()) makes the led blink continuously. Why?? Note that the code is the same for if(a=='A') and if(a=='B'). I really need an explanation for this question.


Solution

  • if(a=='B') will be executed continuously since it stays true until new input is received and it is in loop that is being called repeatedly.

    if(a == 'A') is only evaluated once after a new character is received. If there is no character it is never checked again.

    loop is called repeatedly regardless of whether there is new input available. variable a have global scope so it will not change between calls. It will contain the last received input.