Hardware Reference
In-Depth Information
Figure 6-9:
ASCII table
However, you'll often want to send numeric values to the Arduino. So how
do you do that? You can do so in a few ways. First, you can simply compare the
characters directly. If you want to turn an LED on when you send a
1
, you can
compare the character values like this:
if (Serial.read() == '1')
. Note that
the single quotes around the
'1'
indicate that it should be treated like a character.
A second option is to convert each incoming byte to an integer by subtracting
the zero-valued character, like this:
int val = Serial.read() - '0'
. However,
this doesn't work very well if you intend to send numbers that are greater than 9,
because they will be multiple digits. To deal with this, the Arduino IDE includes
a handy function called
parseInt()
that attempts to extract integers from a
serial data stream. The examples that follow elaborate on these techniques.
Sending Single Characters to Control an LED
Before your dive into parsing larger strings of multiple-digit numbers, start by
writing a sketch that uses a simple character comparison to control an LED.
Search WWH ::
Custom Search