Problem with the Serial.read() command

Hi all guys, i've a problem that i'm trying to resolve by about one hour of coding (the beginner's luck eheh).
I simply want to set ON typing in 'a' and to set it OFF typing another time 'a' but it doesn't function and i don't know the why =(
(i'm using Serial.read like a scanf in C)

Here's the code:

int led = 12;
char val;
 
void setup() {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  
}
 
void loop () 
{  
 
  val = Serial.read();
  
if(val == 'a')
{
 digitalWrite(led, HIGH);
 Serial.write("led ON");
}
val = Serial.read();
  if(val == 'a')
  {
  digitalWrite(led, LOW);
Serial.write("led OFF");
}
  }

Set ON and OFF a led

Is your LED really on pin 12? Usually they are on pin 13.

Bl4ckHound:
and i don’t know the why =(

(i’m using Serial.read like a scanf in C)

check to see that a character has been entered:

if (Serial.available());

then evaluate it:

int led = 13;

void setup() {
  pinMode(led, OUTPUT);
  Serial.begin(9600);

}

void loop () 
{
  if (Serial.available())
  {
    char val = Serial.read();
    if (val == 'a')
    {
      digitalWrite(led,!digitalRead(led));
    }
  }
}
void loop () 
{  
 
  val = Serial.read();
  
if(val == 'a')
{
 digitalWrite(led, HIGH);
 Serial.write("led ON");
}
val = Serial.read();
  if(val == 'a')
  {
  digitalWrite(led, LOW);
Serial.write("led OFF");
}
  }

Loop runs very quickly, and Serial.read() doesn't stop and wait until there is something in the buffer, so you're leaving it up to change as to which Serial.read actually pulls the character out. Rarely, should there be more than one serial read per UART in a given sketch, this isn't one of those times.

if do you use this? http://arduino.cc/en/Reference/SwitchCase

JoeFlowLA:
if do you use this? http://arduino.cc/en/Reference/SwitchCase

was that a question?

The code in the Data Input example in this Thread may give you some ideas.

...R