Lessons · Lesson K5 · Code basics · 30 min
Libraries and modules (I2C, UART)
Install a library, find out which modules are on your I2C wires with a scanner sketch, and see how a UART link differs. About 30 minutes, with a bus you can press.
Two wires, many houses
Think of a long street with a single road. Many houses stand along it, and each house has its own number. The post office (your board) wants to talk to the baker at number 60, so it sends a message down the road with “number 60” on it. Every house hears the message, but only number 60 answers.
That is I2C (said “I squared C”). Two wires carry the traffic of many modules: displays, sensors, clocks. Each module has its own address, like a house number. You will not need a new pin for each one.
Before the road, one more thing: most modules come with a library, a ready-made set of functions written by someone else. It does the hard talking for you, so you can write display.print("hi") and not worry about the bits.
In this lesson you will:
- install a library with the Library Manager,
- connect a module to the two I2C wires and find its address,
- see how a different link, the UART, works with two other wires.
Installing a library
A library is a folder of code you add to the IDE. In Arduino IDE 2 you install it from the Library Manager [1]:
- Open the IDE. In the left column, click the library icon.
- Type the name of the library in the search box. The module’s seller page or datasheet usually tells you which library to use.
- Click INSTALL and wait. It can take up to a minute.
- When it says INSTALLED, it is ready [1].
At the top of a sketch, #include <Name.h> tells the IDE to use it. Almost all libraries bring ready-made examples, which you will find in File > Examples > (library name) [1]. Starting from an example is the quickest way to see that a module works.
Two good habits. Read the library’s example before writing your own code. And check which board the example was written for: you are using an ESP32, so pin numbers may need changing.
One library you do not install: Wire, the I2C library, comes with the ESP32 board package [4], and so does the serial code [8]. You will use both below.
I2C in one screen
I2C uses two wires shared by every device [4]:
- SDA, the data wire,
- SCL, the clock wire.
(Plus power and GND, of course.) One device, the controller (your ESP32), starts every conversation, and the others are peripherals. A peripheral answers only when its own address is called [5][2]. The Wire library uses 7-bit addresses, which go from 0 to 127, and addresses 0 to 7 are reserved, so the first usable one is 8 [2]. Addresses are written in hexadecimal, a counting system with 16 symbols: 0x3C is simply 60 in everyday numbers.
Which pins? On the generic ESP32, the default I2C pins are GPIO21 for SDA and GPIO22 for SCL [4]. Your sketch can also choose other pins with Wire.begin(sdaPin, sclPin) [4]. The sketch below names the pins so there is no doubt.
Pull-ups. The two wires need pull-up resistors, resistors that gently pull each line up to the supply voltage when nobody is talking [4][2]. SparkFun suggests starting from 4.7 kΩ [5]. You will rarely have to add them, because most breakout boards already have them: most of SparkFun’s I2C modules include them [5]. If your module is a bare chip, or its page says it has no pull-ups, add one 4.7 kΩ resistor from SDA to 3V3 and one from SCL to 3V3. If you put many modules on the same wires, there can be too many in parallel [5]. This is rare in beginner projects.
One address per device. Two modules with the same address cannot share the wires [6]. Some modules have a jumper, a solder pad or a pin to choose another address [6].
Where the picture stops. In a real town, houses can have the same number on different streets. On one I2C bus, they cannot. Also, a house number says nothing about what is inside: the same address can mean different chips on different modules, so check the module’s datasheet.
Simulation with example addresses, not a real bus.
Pick or type an address, then press Send.
The same address can mean different chips on different modules: check the datasheet.
Simulation of the scanner sketch: same four example modules.
Press Start scan.
Two modules at 0x3C answer together: the scanner lists the address once.
This is the starting state: the controls need JavaScript.
Before you connect: 3.3 V only
Your ESP32’s pins work at 3.3 V (lesson E4). So use modules that work at 3.3 V. The label on the module or its seller page says so.
A 3.3 V device can usually talk to a 5 V one, but the other way needs care: on some 3.3 V chips, anything above 3.6 V does permanent damage [7]. If you must connect a 5 V module, use a level shifter, a small board made to convert between the two voltages [7].
Power your module from 3V3, even if it says it also accepts 5 V. On many modules the pull-up resistors are tied to the module’s own supply: powered from 5 V, they would pull SDA and SCL up to 5 V, right on your ESP32 pins. Pull-ups must go to the lower of the two voltages [5].
Find your module: the scanner
Connect a 3.3 V I2C module, such as a small display or sensor:
| Module | ESP32 DevKitC |
|---|---|
| VCC (or 3V3) | 3V3 |
| GND | GND |
| SDA | GPIO 21 |
| SCL | GPIO 22 |
Upload this sketch and open the Serial Monitor at 115200 baud:
// Tinker Mission, lesson K5: I2C scanner (find the address of every module on the bus)
// Wiring (use a module that works at 3.3 V):
// Module VCC -> 3V3 Module GND -> GND
// Module SDA -> GPIO 21 Module SCL -> GPIO 22
// Open the Serial Monitor at 115200 baud. The board asks every address from 8 to 127
// "is anybody there?" and prints the ones that answer.
#include <Wire.h>
const int SDA_PIN = 21; // the usual I2C data pin on the ESP32 DevKitC
const int SCL_PIN = 22; // the usual I2C clock pin on the ESP32 DevKitC
void setup() {
Serial.begin(115200);
Wire.begin(SDA_PIN, SCL_PIN); // start the I2C bus on these two pins
}
void loop() {
Serial.println("Scanning...");
int found = 0;
for (byte address = 8; address <= 127; address++) {
Wire.beginTransmission(address); // knock on this address
byte result = Wire.endTransmission(); // 0 means "somebody answered"
if (result == 0) {
Serial.print("Found a device at address 0x");
if (address < 16) {
Serial.print("0"); // keep two digits, like 0x3C or 0x08
}
Serial.println(address, HEX);
found = found + 1;
}
}
if (found == 0) {
Serial.println("No device found. Check power, SDA and SCL wires.");
} else {
Serial.print("Done: ");
Serial.print(found);
Serial.println(" device(s) found.");
}
Serial.println();
delay(5000); // a delay is fine here: this sketch has no other job to do
}
Download the sketch folder (.zip)
You should see something like this (the address depends on your module):
Scanning...
Found a device at address 0x3C
Done: 1 device(s) found.
How it works: for each address from 8 to 127, the board starts a message to that address with Wire.beginTransmission(address) and ends it with Wire.endTransmission(). That function returns 0 if the transmission was a success, and 2 if nobody acknowledged that address [3]. So a 0 means “somebody lives here”. Write down the number: your library will usually ask for it.
UART in one screen
UART is the other common link. Unlike I2C, it uses two wires between just two devices: one wire to send and one to receive. Each device’s TX (send) goes to the other device’s RX (receive), so the wires cross: a transmitter should talk to a receiver, not to another transmitter [9]. Both sides must also agree on the speed, called the baud rate, because there is no clock wire [9]. And the two devices share GND.
You already use a UART: the board’s first UART, called UART0, reaches your computer’s USB cable through a small USB-to-serial chip [10][8]. It is used for programming and for the Serial Monitor [8]. It is the Serial object. The ESP32 also has other UARTs, called Serial1 and Serial2, for general use [8].
You choose the pins when you start one: Serial2.begin(baud, SERIAL_8N1, rxPin, txPin) [8]. SERIAL_8N1 is the usual format [9]. Try it without any module: a jumper wire from GPIO 23 (TX2) to GPIO 32 (RX2) makes the board listen to itself.
// Tinker Mission, lesson K5: UART test with Serial2 (a loopback, no module needed)
// Wiring: one jumper wire between GPIO 23 (TX2, sends) and GPIO 32 (RX2, receives).
// The board talks to itself: what it sends on TX2 comes back in on RX2.
// Open the Serial Monitor at 115200 baud. Remove the jumper and the "received" lines stop.
const int RX2_PIN = 32; // Serial2 receives here
const int TX2_PIN = 23; // Serial2 sends from here
const unsigned long SEND_INTERVAL = 2000; // send a message every 2000 ms
unsigned long lastSend = 0;
int counter = 0;
void setup() {
Serial.begin(115200); // the USB link to your computer
Serial2.begin(9600, SERIAL_8N1, RX2_PIN, TX2_PIN); // speed, format, receive pin, send pin
}
void loop() {
unsigned long now = millis();
// Send one short line every 2 seconds.
if (now - lastSend >= SEND_INTERVAL) {
lastSend = now;
Serial2.print("hello ");
Serial2.println(counter);
Serial.print("sent: hello ");
Serial.println(counter);
counter = counter + 1;
}
// Read whatever arrived on Serial2.
if (Serial2.available() > 0) {
String line = Serial2.readStringUntil('\n');
line.trim(); // remove the end-of-line characters
Serial.print("received: ");
Serial.println(line);
}
}
Download the sketch folder (.zip)
Every two seconds you should see a “sent” line, followed by a “received” line. A stray odd character at the very start, or when you move the jumper, is normal. Remove the jumper: the “received” lines stop, since nobody is listening.
GPS modules, fingerprint sensors and many others speak UART. For those, remember the crossing: their TX goes to your RX pin.
Try your own changes
Change one thing, then observe.
- Count the devices. Unplug the USB cable, then connect a second 3.3 V I2C module to the same SDA, SCL, 3V3 and GND lines, in parallel. Plug the cable back in. Does the scanner find two addresses? What happens if they are the same?
- Unplug a wire. Pull the SCL wire while the scanner runs. What does the Serial Monitor say?
- A faster UART. In the loopback sketch, change
9600to115200inSerial2.begin. Does it still work? Why, given that both ends are the sameSerial2?
When it does not work
- “No device found”. Check power (3V3, not 5 V) and GND. Check that SDA goes to GPIO 21 and SCL to GPIO 22, and that they are not swapped. If your module has no pull-ups, add them as shown above.
- The address is not what the module says. Some modules have address pads or jumpers [6]. Use the number the scanner finds.
- Two modules, only one shows up. They may have the same address [6]. Look for an address jumper or pad.
- The scanner finds something, but the example sketch does not work. Check that the sketch uses your pins and the address the scanner found, and that the library is installed.
- UART: only garbage characters. Both sides must use the same baud rate [9].
- UART: nothing arrives. TX and RX must cross [9], and the two boards must share
GND. - Nothing in the Serial Monitor. Set it to 115200 baud, as in
Serial.begin(115200).
Check yourself
Three short questions. Nothing is saved, take your time.
Where do you install a library in the Arduino IDE 2?
- In the library manager, opened from the library icon in the left column
- In the Serial Monitor
- You must rewrite the library yourself
Two I2C modules both answer at address 0x3C. What is the problem?
- None, the board tells them apart by their colour
- Each device on the same I2C wires needs its own address, so they will clash
- The addresses only matter for UART
You connect a module that works at 5 V to ESP32 pins directly. What should you check first?
- Whether its signals go above 3.3 V: the ESP32's pins are made for 3.3 V, and some 3.3 V chips are damaged above 3.6 V
- Nothing, 5 V and 3.3 V are the same
- That the module is the same colour as the board
Show the answer
Whether its signals go above 3.3 V: the ESP32's pins are made for 3.3 V, and some 3.3 V chips are damaged above 3.6 V. Going from a 5 V device to a 3.3 V one needs care: on some 3.3 V chips, voltages above 3.6 V cause permanent damage [7]. Use a module made for 3.3 V, or a level shifter [7].
In short
- In Arduino IDE 2, install a library from the Library Manager, then look in File > Examples [1].
- I2C uses two shared wires, SDA and SCL. The controller calls an address and only that peripheral answers [4][2].
- On the generic ESP32 the default pins are GPIO21 (SDA) and GPIO22 (SCL), and you can choose others [4].
- The wires need pull-up resistors, which many modules already include [4][5].
- Every device on a bus needs its own address. Run a scanner to find it [6][3].
- Use 3.3 V modules, or a level shifter [7].
- UART uses two wires between two devices, with TX to RX crossing, and the same baud rate [9][8], and a common GND.
Next steps: Wi-Fi and radio (W1), or the distance and camera modules in S3.
Sources
Show the 10 sources
- Arduino, “Installing libraries” (Arduino IDE 2: click the library icon in the left column, search, press INSTALL, status becomes INSTALLED; examples under File > Examples > library > example) — https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-installing-a-library/
- Arduino, Language Reference, “Wire” (the library uses 7-bit addresses; addresses 0 to 7 are reserved so the first usable address is 8; pull-up resistors are needed on SDA and SCL; controller and peripheral roles) — https://docs.arduino.cc/language-reference/en/functions/communication/wire/
- Arduino, Language Reference, “Wire.endTransmission()” (returns 0 for success and 2 when a NACK was received on transmit of the address) — https://docs.arduino.cc/language-reference/en/functions/communication/wire/endTransmission/
- Espressif, Arduino-ESP32 documentation, “I2C” (two wires, SDA and SCL, many devices each with a unique 7-bit address; the lines require pull-up resistors; setPins and begin can choose the pins; on the generic ESP32 the default pins are GPIO21 for SDA and GPIO22 for SCL) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/i2c.html
- SparkFun, “I2C” (two signals SDA and SCL; pull-up on each line, start with 4.7 kΩ and adjust; most SparkFun I2C devices include pull-ups, and with many devices you may need to disconnect some; in mixed-voltage systems, connect the pull-ups to the lower voltage) — https://learn.sparkfun.com/tutorials/i2c
- Adafruit, “I2C Addresses and Troublesome Chips” (each I2C device must have a unique address from 0 to 127; two devices with the same address cannot share the lines; workarounds include an address-select line or jumper) — https://learn.adafruit.com/i2c-addresses
- SparkFun, “Logic Levels” (a 3.3 V device can interface with a 5 V device; the other way, check that the 3.3 V device is 5 V tolerant, since above 3.6 V some can be permanently damaged; use a voltage divider or a level shifter) — https://learn.sparkfun.com/tutorials/logic-levels
- Espressif, Arduino-ESP32 documentation, “Serial (UART)” (UART0 is typically used for programming and the Serial Monitor; Serial1, Serial2 for general-purpose communication; begin(baud, config, rxPin, txPin)) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/serial.html
- SparkFun, “Serial Communication” (TX goes to the other device’s RX and vice versa; both sides must use the same baud rate; 8N1 format) — https://learn.sparkfun.com/tutorials/serial-communication
- Espressif, ESP32-DevKitC User Guide (the board has a USB-to-UART bridge chip; its micro-USB port carries power and the communication between a computer and the ESP32 module) — https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32/esp32-devkitc/user_guide.html