pin 13 on with ASCII e then off 1 sec

Hello to all, I want to create a serial communication with arduino one: pin 13 to switch it up after sending the ASCII character "L" and wear it again after 1 second to zero. The software continues to run the loop on and off and I can not understand the reason for which I do not run once the cycle.

char val; ** *int ledpin = 13; //Impostate il pin LED che preferite * *void setup() { * ** pinMode(ledpin, OUTPUT); ** ** Serial.begin(9600); ** **} void loop() { ** ** if( Serial.available() ) ** ** { ** ** val = Serial.read(); } ** ** if( val == 'L' ) { ** digitalWrite(ledpin, HIGH); ** ** delay(1000);** digitalWrite(ledpin, LOW); } ** ** else { ** ** digitalWrite(ledpin, LOW); } ** ** delay(100); ** **}

Once you have read val from serial it remains set even when nothing is available, so the LED comes on again next time through loop() having been off for 100 mS

Put the conditionally executed code inside the conditional!!

And always declare variables as local as possible, like this:

const int ledpin = 13; //Impostate il pin LED che preferite 

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

void loop()
{ 
  if (Serial.available())   
  { 
    char val = Serial.read() ; // val only used in this scope, so declare it here
    if (val == 'L')
    {
       digitalWrite (ledpin, HIGH);   
       delay (1000);
       digitalWrite (ledpin, LOW);
    }  
  } 
  else
  {   
    digitalWrite (ledpin, LOW);  // this is not strictly needed now
  } 
  delay (100);   
}

Its important to make code readable by plenty of whitespace (blank lines, spaces), and indent blocks correctly, match up parentheses visually so you can see the structure at a glance.