Français

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:

  1. install a library with the Library Manager,
  2. connect a module to the two I2C wires and find its address,
  3. see how a different link, the UART, works with two other wires.
I2C: one road, many houses A straight street seen from above, drawn flat. On the left, the board as the post office. Two parallel roads, labelled SDA and SCL, run to the right past four houses with example numbers on their doors: 0x3C, 0x48, 0x68 and 0x77. Each house is joined to both roads. A letter labelled to 0x48 travels along the roads: every house hears it, only house 0x48 answers, and it is lit. The numbers are examples: your module's address is in its datasheet, or the scanner finds it. 0x3C is simply 60 written in hexadecimal. FIG. 1 — THE I2C STREETpost office= your board(controller)SDASCLSDA: data · SCL: clock0x3Chears it, stays quiet0x48answers: here!0x68hears it, stays quiet0x77hears it, stays quietto 0x48Example numbers. One address per house on the same road: two modules with the same number clash.0x3C is 60 written in hexadecimal. The scanner finds your module's number.
Tap the diagram to open it full screen.

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]:

  1. Open the IDE. In the left column, click the library icon.
  2. Type the name of the library in the search box. The module’s seller page or datasheet usually tells you which library to use.
  3. Click INSTALL and wait. It can take up to a minute.
  4. 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.

Send a message on the I2C bus (interactive)
Send a message on the I2C bus (interactive) Interactive simulation, not a real bus. Left, the controller, your ESP32. Two lines, SDA and SCL, run to the right past four modules drawn as houses with the example addresses 0x3C, 0x48, 0x68 and 0x77. Pick or type an address and press Send: a letter travels down the lines, every house flashes as it passes, and only the house with that address answers with a small ACK flag. An address nobody has gets no answer. With the toggle Two devices with the same address, the last house becomes 0x3C too: both reply at once and a clash mark shows. The Scanner tab asks every address from 8 to 127 and lists the ones that answered. simulation, example addressesESP32controllerSDASCL0x3C0x480x680x77only the matching address answers

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.

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].

3.3 V modules only, or a level shifter Two panels side by side. a, 3.3 V module: OK, with a green tick. The module's VCC goes to 3V3, GND to GND, SDA to GPIO 21 and SCL to GPIO 22, straight to the ESP32. b, 5 V module: needs a level shifter, with an orange warning. A small level shifter board sits between the module and the ESP32: its high-voltage side, 5 V, faces the module; its low-voltage side, 3.3 V, faces the ESP32. On some 3.3 V chips, anything above 3.6 V does permanent damage. Power a module from 3V3 when it accepts it: its pull-ups follow its supply. FIG. 2 — BEFORE YOU CONNECTa3.3 V module: OKESP323V3GND21223.3 V moduleVCCGNDSDASCLstraight to the ESP32power it from 3V3b5 V module: needs a level shifterESP323V3GND2122level shifterLVHV5 V moduleSDASCL3.3 V side5 V side!above 3.6 V can damage some 3.3 V chipspower and GND wires not drawnPower the module from 3V3 when it accepts it: its pull-ups follow its supply, and must not reach 5 V.
Tap the diagram to open it full screen.

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
K5 wiring: an I2C module on 3V3, GND, 21 and 22 Two panels. a, the DevKitC seen from above, USB on the left, off the breadboard: GPIO 21 and 22 are on its bottom header, so female jumpers go straight on the pins, and a breadboard is not needed. A 3.3 V I2C module on the right, pins VCC, GND, SDA and SCL. Four numbered wires: 1 red, 3V3 to VCC; 2 black, GND to GND; 3 blue, GPIO 21 to SDA; 4 yellow, GPIO 22 to SCL. Use a module that works at 3.3 V; check the pin order printed on yours. b, the Serial Monitor at 115200 baud after uploading the scanner: Scanning..., Found a device at address 0x3C, Done: 1 device(s) found. The address depends on your module. FIG. 3 — WIRING AND SCANNER OUTPUTaWiringENBOOT5VCLKCMDD0D3D1D215132GND0124141627172652518331932GND352134RXVNTXVP22EN233V3GNDI2C module, 3.3 VVCCGNDSDASCLGND3V3GND2122GND1234check the pin order on yours1red: 3V3 → VCC (not 5 V)2black: GND → GND3blue: GPIO 21 → SDA (data)4yellow: GPIO 22 → SCL (clock)21 and 22 are on the bottom header: female jumpers straight on the pins, no breadboard needed.bWhat the scanner printsSerial Monitor · 115200 baudScanning...Found a device at address 0x3CDone: 1 device(s) found.The address dependson your module.Write it down: your librarywill usually ask for it.
Tap the diagram to open it full screen.

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)

UART loopback: GPIO 23 talks to GPIO 32 Three panels. a, the DevKitC seen from above, USB on the left, no module: one female-to-female jumper wire runs from GPIO 23 on the bottom header, TX2, the pin that sends, round the end of the board to GPIO 32 on the top header, RX2, the pin that receives. The board talks to itself. b, the Serial Monitor at 115200 baud: sent: hello 0, received: hello 0, sent: hello 1, received: hello 1. Remove the jumper and the received lines stop. c, with two devices, the wires cross: each TX goes to the other's RX, both use the same baud rate, and they share GND. FIG. 4 — UART LOOPBACKaOne jumper, no moduleENBOOT5VCLKCMDD0D3D1D215132GND0124141627172652518331932GND352134RXVNTXVP22EN233V3GND322332 = RX2 (receives)23 = TX2 (sends)data flows23 → 32bSerial MonitorSerial Monitor · 115200 baudsent: hello 0received: hello 0sent: hello 1received: hello 1cTwo devices: the wires crossboardTXRXGNDmoduleTXRXGNDsame baud rate, shared GND
Tap the diagram to open it full screen.

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.

  1. 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?
  2. Unplug a wire. Pull the SCL wire while the scanner runs. What does the Serial Monitor say?
  3. A faster UART. In the loopback sketch, change 9600 to 115200 in Serial2.begin. Does it still work? Why, given that both ends are the same Serial2?

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.

  1. 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
    Show the answer

    In the library manager, opened from the library icon in the left column. In IDE 2 you click the library icon in the left column, search, and press INSTALL [1]. Once installed, the library's examples are under File > Examples [1].

  2. 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
    Show the answer

    Each device on the same I2C wires needs its own address, so they will clash. Each I2C device on a bus must have a unique address, so two with the same address cannot share the same two wires [6]. Some modules have a jumper or an address-select pin to change theirs [6].

  3. 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
  1. 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/
  2. 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/
  3. 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/
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.