Lesson 11: Serial Line Communications


All Arduino boards have at least one serial port (also know as UART or USART).

The communicate on digital pins 0 (RX) and 1 (TX) as well as the computer via USB.

Therefore, if you use the Serial communications functions, you cannot use pins 0 and 1 for digital input or output.

Arduino-to-Arduino Serial Communication

You can use the Arudino environment's built-in serial monitor to communicate with an Arduino board

Serial Monitor

 

Use the same baud rate as you used in Serial.begin().

Serial.begin() - Sets the data rate in bits per second (baud) for serial data transmission
Serial.available() - Gets the number of bytes (characters) available for reading from the serial port.
Serial.peek() - Returns the next byte (character) of incoming serial data without removing it from the queue.
Serial.print() - Prints data to the serial port.
Serial.read() - Reads incoming serial data.

Receiving A Message

void setup() {
Serial.begin(9600); // Set the baud rate.
// Must be the same at transmitting Arduino.
}
void loop() {
String message = "";

// Check the message queue
if (Serial.peek() != -1) {
// Incoming message on the queue
while(Serial.available()) {
// Read the data from the queue one character at a time
char incomingCharacter = (char)Serial.read();
message += incomingCharacter;
}

// Message received. Now, do something with that message.
if (message.equals("stop")) {
// Do whatever you need to do
// . . .
} else if (message.equals("start")) {
// Do whatever you need to do
// . . .
}
}
}

Sending A Message

void setup() {
Serial.begin(9600); // Set the baud rate.
// Must be the same at transmitting Arduino.
}
void loop() {
// Send a message
Serial.print("stop");
}