I am trying to control an led which uses arduino and the serial. How should I alter this code to make it so that when I enter a character the led goes on and when i enter a character again the led goes off?
int led = 13;
int led_state = 0;
void setup()
{
pinMode(led,OUTPUT);
Serial.begin(9600);
digitalWrite(led,LOW);
}
void loop()
{
if (Serial.available()>0)
{
if (digitalRead(led))
{digitalWrite(led,!digitalRead(led));}
digitalWrite(led,HIGH);
Serial.flush();
}
}
I'd use a proper terminal emulator, like puTTY instead.
That way, you don't need to hit "send" every time you hit a key; it's sent automatically as soon as you press the key-
So, you've already done one comparison to see if there's anything there to read.
So now read it into a variable and then compare what you read with a value .
Depending on which version of the IDE you have, the flush may not be doing what you think it is.