Hardware Reference
In-Depth Information
pinMode ( LED , OUTPUT );
Serial . begin ( 9600 );
}
void loop () {
if ( Serial . available ()) { //
char c = Serial . read (); //
if ( c == 'h' ) {
digitalWrite ( LED , HIGH );
}
if ( c == 'l' ) {
digitalWrite ( LED , LOW );
}
}
}
If there are characters available in the serial buffer, execute the code
in the block.
Create a new char variable called c and store the next byte from the
serial buffer in it. This will remove it from the serial buffer.
In the Arduino IDE, open the serial monitor by clicking the magnifying glass
button on the upper right side of the window. In the input text box at the top
of the serial monitor, enter a lowercase h or l and click Send. The on-board
LED connected to pin 13 should turn on when you send the “h”, and it should
turn off when you send an “l.” Sending any other character should have no
effect on the LED.
The function Serial.available() returns the number of bytes in the serial
buffer. If there are none, the if statement in Example 5-1 will evaluate as false
and the code in the block won't be executed. Any value other than 0 will
evaluate as true.
The function Serial.read() will return the next byte in the serial buffer, which
removes it from the buffer.
Taking It Further
With everything this topic has covered so far, you should be able to under-
stand most of the examples that are included with the Arduino IDE. However,
it can take some practice to really cement these concepts. Here are a few
ideas to help you do just that:
• To learn more about loops and other control structures, take a look at
the examples included with the Arduino IDE that explore these concepts.
Click File Examples 05.Control.
• One of the control examples relates to the switch and case keywords,
which work together to help you evaluate for a few different conditions
Search WWH ::




Custom Search