13.9 Serial communication
The USB cable carries more than power and firmware. While a program runs, the ESP32 and the computer exchange text over it: every Serial.println() so far has used that link, and the bench programs of the servo and motor chapters read commands from it. This chapter turns the link around. We type commands that switch and blink an LED, plot a signal in Teleplot, and then look at what travels on the wire and how a program reads a line without stopping everything else.
The Guide
Step 1: Upload and listen
The project is code/serial next to this chapter, a copy of blink with a new main.cpp:
// main.cpp: talk to the board from the Serial Monitor. Type a command and press Enter.
// on | off switch the LED on GPIO 2
// blink <ms> blink, <ms> on and <ms> off
// wave plot a sine wave in Teleplot
// stop stop blinking and plotting
#include <Arduino.h>
const int ledPin = 2;
enum Mode { STILL, BLINK, WAVE };
Mode mode = STILL;
int blinkMs = 500;
bool ledOn = false;
unsigned long lastMs = 0;
String line = ""; // the characters received since the last Enter
void displayHelp() {
Serial.println("Commands: on | off | blink <ms> | wave | stop");
}
void setLed(bool on) {
ledOn = on;
digitalWrite(ledPin, on ? HIGH : LOW);
}
void handleLine(String s) {
s.trim(); // drop spaces and the line ending
if (s.length() == 0) return;
if (s == "on") { mode = STILL; setLed(true); Serial.println("LED on"); return; }
if (s == "off") { mode = STILL; setLed(false); Serial.println("LED off"); return; }
if (s == "wave") { mode = WAVE; return; }
if (s == "stop") { mode = STILL; Serial.println("stopped"); return; }
// A command with a number, such as "blink 200"
int sp = s.indexOf(' '); // the space between word and number
if (sp < 0) { displayHelp(); return; }
String cmd = s.substring(0, sp);
int val = s.substring(sp + 1).toInt(); // 0 when the rest is not a number
if (cmd == "blink" && val > 0) {
mode = BLINK;
blinkMs = val;
Serial.printf("blinking, %d ms on and %d ms off\n", val, val);
} else {
displayHelp();
}
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
displayHelp();
}
void loop() {
// Collect characters until Enter, then handle the line
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') { handleLine(line); line = ""; }
else if (line.length() < 64) { line += c; }
}
if (mode == BLINK && millis() - lastMs >= blinkMs) {
lastMs = millis();
setLed(!ledOn);
}
if (mode == WAVE && millis() - lastMs >= 20) { // 50 points per second
lastMs = millis();
float t = millis() / 1000.0; // time in seconds
Serial.printf(">sine:%.3f\n", sin(2 * PI * 0.5 * t)); // one period every 2 s
}
}Build and upload it, then open the Serial Monitor with the settings of Step 7 of the setup: the board’s COM port, 115200 baud and line ending LF. Press the EN button on the board. A few lines starting with rst:0x1 and boot:0x13 appear first, printed by the chip’s own start-up code before our program runs, and then our help line:
Commands: on | off | blink <ms> | wave | stop
Step 2: Send commands
Type on in the box at the bottom of the Serial Monitor and press Enter. The blue LED marked D2 lights, and the board answers LED on. Then try, one at a time:
off
blink 200
blink 50
blink fast
stop
blink 200 blinks five times a second, blink 50 twenty. blink fast prints the help line, since fast is not a number, and the LED keeps blinking at the old rate until stop. While the LED blinks, the board still answers every command at once: nothing in loop() waits.
Step 3: Plot in Teleplot
Type wave. The monitor fills with lines like >sine:0.482, fifty a second. Click Stop Monitoring, open Teleplot from the status bar, choose the COM port and 115200 and click Open. A chart named sine draws one period every two seconds. Teleplot plots every line of the form >name:value and lists all other lines in its console, so the help line and the answers to commands appear there as text.
To stop the wave, close the port in Teleplot, start the Serial Monitor again and type stop. Only one program at a time can hold the port.
Step 4: The wrong baud rate
Stop the board’s output with stop. In the Serial Monitor set the baud rate to 9600, start monitoring and press EN. The help line arrives as a short string of odd characters, and typed commands have no effect. Set 115200 again and press EN: the text is back. Both ends must use the same rate, and One character on the wire shows why.
How It Works
From USB to two wires
The ESP32 has no USB of its own. On the DevKit a small chip next to the connector, the CH340 on the boards in the lab kits, translates between USB and a serial port of the ESP32, called a UART (universal asynchronous receiver-transmitter). The UART uses two wires: TX, on which the ESP32 transmits, on GPIO 1, and RX, on which it receives, on GPIO 3. Uploading a program uses the same two wires, which is why the Serial Monitor must release the port before every upload. In the program the port is the object Serial, and Serial.begin(115200) starts it at 115 200 bits per second.
One character on the wire
Between characters the TX line rests high, at 3.3 V. A character starts with a start bit, one bit time at 0 V, followed by the eight bits of the character with the lowest bit first and a stop bit at 3.3 V (Figure 13.9.1). Ten bit times carry eight bits of data. At 115 200 baud one bit lasts \(1/115\,200\) s = 8.68 µs, so one character takes 86.8 µs, and the link carries at most
\[ \frac{115\,200}{10} = 11\,520~\text{characters per second}. \]
A (65, binary 0100 0001) leaving the ESP32 on TX at 115 200 baud. The falling edge of the start bit starts the receiver’s clock, and the dots mark where it samples each bit, in the middle of its bit time.
No clock travels with the data, which is the asynchronous in UART. The receiver waits for the falling edge of the start bit, waits one and a half bit times to reach the middle of bit 0, and then samples once per bit time. Both ends must therefore agree on the bit time in advance. A receiver set to 9600 baud expects bits twelve times longer than the ones that arrive, samples the wrong places, and assembles characters that were never sent. That is the garbage of Step 4. A mismatch of a few percent is tolerated, since the sample of the last bit only has to stay inside that bit.
Text, not numbers
Serial.print(1234) does not send the number 1234. It sends the four characters 1, 2, 3 and 4, as the character codes 49, 50, 51 and 52, so that the Serial Monitor can show them as they are. Serial.println() adds two more characters, a carriage return \r and a line feed \n, which end the line. Serial.printf() builds a whole line from a template: in "blinking, %d ms on\n" the %d is replaced by a whole number, %.3f by a decimal number with three decimals and %s by a piece of text. A float printed with %.3f costs a few more characters than the bits it holds, but every program and every person can read it.
The same text carries the plots. Teleplot reads each line, and a line that starts with >, then a name, a colon and a number becomes a point on the chart with that name. A program can print several such lines, one per signal, and Teleplot draws one chart for each name.
Reading a line
What we type in the Serial Monitor is sent when we press Enter, followed by the line ending, here \n. The characters arrive in the ESP32 one by one and wait in a receive buffer until the program reads them. Serial.available() tells how many are waiting, and Serial.read() takes the oldest one.
The while loop at the top of loop() takes every waiting character. An ordinary character is appended to line; a \n or \r means the line is complete, so handleLine() gets it and line starts empty again. A monitor that ends lines with \r\n sends both, and the second one produces an empty line, which handleLine() ignores. The limit of 64 characters keeps a stream of garbage, such as the output of a wrong baud rate, from filling the memory.
The loop takes only what has already arrived and never waits for the rest. Arduino also offers Serial.readStringUntil('\n'), which reads a whole line in one call, but it returns only when the \n arrives or after a timeout of one second. With the line ending set to None every command would cost a second in which loop() does nothing else, no blinking, no plotting and, on the car, no steering. Reading character by character costs a few more lines and keeps the loop free. The servo bench and the motor bench read their commands the same way.
Splitting a command
handleLine() first removes spaces and line endings at both ends with trim() and compares the line with the commands that have no number: on, off, wave, stop. A command with a number has a space in it. indexOf(' ') finds the space, substring(0, sp) is the word before it, and substring(sp + 1).toInt() turns the rest into a whole number. toInt() returns 0 when the text is not a number at all, so blink fast gives val = 0, and the test val > 0 refuses it. The servo bench uses exactly this shape, with u 1500 in place of blink 200.
Printing takes time
The link carries 11 520 characters a second, and each line of the wave takes about 13 characters, so fifty lines a second use less than a twentieth of it. A program that prints a long line in every pass of a fast loop fills the link instead. The characters then queue in a small buffer, and once it is full, print() waits until there is room. The program slows down to the speed of the serial port without any warning. This is why the bench programs print five or ten times a second and not in every pass of loop().
Exercises
Exercise 1: A status command
Add a command ? that prints the mode, the blink time and how long the board has been running, from millis(), in one line with Serial.printf().
Exercise 2: Two signals in one chart
Let wave print a second line, >square: followed by 1 when the sine is positive and 0 otherwise. Look at both in Teleplot. How many characters per second does the board send now, and what fraction of the link is that?
Exercise 3: The bits on the oscilloscope
Connect the oscilloscope probe to the RX pin and ground. That pin carries what the computer sends to the ESP32. Type UUUU in the Serial Monitor and press Enter. Find the start bit of a character and measure one bit time. Compare with 8.68 µs. Why is U (85, binary 0101 0101) a good character for this measurement?
Exercise 4: How long does a print take?
Measure with micros() before and after Serial.println() of a 40-character line, once and then ten times in a row. Explain the difference between the two results with Printing takes time.