Hardware Reference
In-Depth Information
Listing 6-4: Single LED Control using Characters—single_char_control.ino
//Single Character Control of an LED
const int LED=9;
char data; //Holds incoming character
void setup()
{
Serial.begin(9600); //Serial Port at 9600 baud
pinMode(LED, OUTPUT);
}
void loop()
{
//Only act when data is available in the buffer
if (Serial.available() > 0)
{
data = Serial.read(); //Read byte of data
//Turn LED on
if (data == '1')
{
digitalWrite(LED, HIGH);
Serial.println("LED ON");
}
//Turn LED off
else if (data == '0')
{
digitalWrite(LED, LOW);
Serial.println("LED OFF");
}
}
}
Note that an else if statement is used instead of a simple else statement.
Because your terminal is also set to send a newline character with each trans-
mission, it's critical to clear these from the buffer. Serial.read() will read in
the newline character, see that is not equivalent to a '0' or a '1' , and it will be
overwritten the next time Serial.read() is called. If just an else statement were
used, both '0' and '\n' would trigger turning the LED off. Even when sending
a '1' , the LED would immediately turn off again when the '\n' was received!
Search WWH ::




Custom Search