Simulation is correct but

hi

i know its a simple project but i cant understand why its working in simuliation but in arduino its not

if i type '1' in serial number i want to turn on and off each led and when i type '2' it should turn off the led that is on.

char data=0;

void setup()

{
Serial.begin(9600);

for(int i=2;i<10;i++)
{

pinMode(i,OUTPUT);

}

}

void loop()

{
for(int i=2;i<10;i++)

{

if(Serial.available())

{

  data=Serial.read();

}

if(data== '1')

{

  digitalWrite(i,1);

  delay(500);

  digitalWrite(i,0);

}

else if(data=='2')

{

  for(int i=2;i<10;i++){

    digitalWrite(i,0);

  }

  break;

  

}

}

delay(1);

}

This looks like a premise for random behaviour

Please remember to use code tags when posting code

is this the same school exercise as

Do you have "No line ending" selected in the menu at the bottom of Serial Monitor? If not, the line ending characters are keeping the '1' from continuing to be the latest character received.

char data = 0;

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

  // LED's on pins 2 through 9
  for (int i = 2; i < 10; i++)
  {
    pinMode(i, OUTPUT);
  }
}

void loop()
{
  for (int i = 2; i < 10; i++)
  {
    if (Serial.available())
    {
      data = Serial.read();
    }

    if (data == '1')
    {
      // Turn on 'the current LED' for half a second
      digitalWrite(i, 1);
      delay(500);
      digitalWrite(i, 0);
    }
    else if (data == '2')
    {
      // Turn off all LEDs
      for (int i = 2; i < 10; i++)
      {
        digitalWrite(i, 0);
      }
    }
  }
}
1 Like

no line ending is a solution thank you :pray: :pray: