Sub topic 1
How an Arduino talks to your computer
Prerequisites
This chapter assumes you can write and upload a basic sketch with setup() and loop(), and that you know variables, data types, if statements, analogRead, and digitalWrite. You should also have the Arduino IDE installed and a board connected by USB.
How the connection works
An Arduino sends text to your computer over a serial link. On most boards, the USB cable carries these bytes through a UART (a chip or circuit that sends data one bit at a time). The Arduino IDE then displays the bytes in the Serial Monitor.
Starting serial with Serial.begin and choosing a baud rate
Call Serial.begin() once in setup(). The number you pass is the baud rate, which is the bits per second the board sends. The most common value is 9600.
void setup() {
Serial.begin(9600);
}
void loop() {
}Opening and using the Serial Monitor
Steps
- Upload the sketch to the board.
- Open the Serial Monitor from the Tools menu or the magnifier icon.
- Set the baud rate in the lower-right corner to match
Serial.begin. - Check the line-ending setting if you plan to send commands later.
Printing text and values with print and println
Serial.print() writes text without a line break. Serial.println() adds a newline at the end. Wrap fixed text in F() to save RAM.
void setup() {
Serial.begin(9600);
Serial.println(F("Setup complete"));
int count = 42;
Serial.print(F("Count: "));
Serial.println(count);
Serial.println(count, HEX);
}
void loop() {
Serial.println(millis());
delay(1000);
}The optional second argument selects the format for integers:
| Call | Output |
|---|---|
| `Serial.println(42)` | 42 |
| `Serial.println(42, HEX)` | 2A |
| `Serial.println(42, BIN)` | 101010 |
Exercise
Write a sketch that prints the number 255 in HEX and in BIN. What does each line show?
Show answer
Use Serial.println(255, HEX), which prints FF, and Serial.println(255, BIN), which prints 11111111.