For uploading software, the Arduino has a serial port, and you can use it to
connect the Arduino to other devices, too. (In Compiling and Uploading Pro-
grams, on page 19, you learned how to look up the serial port your Arduino
is connected to.) In this section, you’ll use the serial port to control Arduino’s
status LED using your computer’s keyboard. The LED should be turned on
when you press 1, and it should be turned off when you press 2. Here’s all
the code you need:
Welcome/LedSwitch/LedSwitch.ino
const unsigned int LED_PIN = 13;
Line 1
const unsigned int BAUD_RATE = 9600;
-
-
void setup() {
-
pinMode(LED_PIN, OUTPUT);
5
Serial.begin(BAUD_RATE);
-
}
-
-
void loop() {
-
if (Serial.available() > 0) {
10
int command = Serial.read();
-
if (command == '1') {
-
digitalWrite(LED_PIN, HIGH);
-
Serial.println("LED on");
-
} else if (command == '2') {
15
digitalWrite(LED_PIN, LOW);
-
Serial.println("LED off");
-
} else {
-
Serial.print("Unknown command: ");
-
Serial.println(command);
20
}
-
}
-
}
-
As in our previous examples, we define a constant for the pin the LED is
connected to and set it to
OUTPUT
mode in the
setup
function. In line 6, we ini-
tialize the serial port using the
begin
function of the
Serial
class, passing a baud
rate of 9600. (You can learn what a baud rate is in Learning More About
Serial Communication, on page 253.) That’s all we need to send and receive
data via the serial port in our program.
So, let’s read and interpret the data. The
loop
function starts by calling
Serial
’s
available
method in line 10.
available
returns the number of bytes waiting on the
serial port. If any data is available, we read it using
Serial.read
.
read
returns the
first byte of incoming data if data is available and -1 otherwise.
If the byte we have read represents the character 1, we switch on the LED
and send back the message “LED on” over the serial port. We use
Serial.println
,
report erratum • discuss
Using Serial Ports • 29
www.it-ebooks.info