Hardware Reference
In-Depth Information
Listing 6-3: Arduino Serial Echo Test—echo.ino
//Echo every character
char data; //Holds incoming character
void setup()
{
Serial.begin(9600); //Serial Port at 9600 baud
}
void loop()
{
//Only print when data is received
if (Serial.available() > 0)
{
data = Serial.read(); //Read byte of data
Serial.print(data); //Print byte of data
}
}
Launch the serial monitor and type anything you want into the text entry
field. As soon as you press Send, whatever you typed is echoed back and dis-
played in the serial monitor. You have already selected to append a “newline”
to the end of each command, which will ensure that each response is on a new
line. That is why Serial.print() is used instead of Serial.println() in the
preceding sketch.
Understanding the Differences Between Chars and Ints
When you send an alphanumeric character via the serial monitor, you aren't actu-
ally passing a “5”, or an “A”. You're sending a byte that the computer interprets
as a character. In the case of serial communication, the ASCII character set is
used to represent all the letters, number, symbols, and special commands that
you might want to send. The base ASCII character set, shown in Figure 6-9, is a
7-bit set and contains a total of 128 unique characters or commands.
When reading a value that you've sent from the computer, as you did in
Listing 6-3, the data must be read as a char type. Even if you are only expecting
to send numbers from the serial terminal, you need to read values as a character
first, and then convert as necessary. For example, if you were to modify the code
to declare data as type int , sending a value of 5 would return 53 to the serial
monitor because the decimal representation of the character 5 is the number
53. You can confirm this by looking at the ASCII reference table in Figure 6-9.
Search WWH ::




Custom Search