Skip to content
systemcoding.dev
Embedded

Read an I2C Sensor on Raspberry Pi Pico With i2c_read_blocking

Read a TMP102 sensor on a Raspberry Pi Pico with i2c_init, i2c_write_blocking and i2c_read_blocking, using nostop for the repeated start.

7 min read
Summarize in AI
Flat illustration of a single-board computer with its SoC, memory, header and ports, with the Raspberry Pi, Arm and C logos.

The Raspberry Pi Pico C SDK exposes the RP2040's two I2C controllers through a small set of functions. A sensor read is two of them: write the register to read, then read the data back, with a flag that keeps the bus between the two so the transaction uses a repeated start. This post wires a Texas Instruments TMP102 digital temperature sensor to a Pico, reads its temperature register with i2c_write_blocking and i2c_read_blocking from Pico SDK 2.0, converts the raw value to degrees, and covers the pin choices, the pull-up handling, error returns and timeouts. The I2C basics are in the guide to I2C and the addressing post in this cluster.

The controllers and pins

The RP2040 has two I2C blocks, i2c0 and i2c1, each a Synopsys DesignWare I2C controller. Any GPIO can serve as I2C, but each pin belongs to one of the controllers' SDA or SCL roles in a fixed pattern. For i2c0, SDA is on GPIO 0, 4, 8, 12, 16 or 20, and SCL on GPIO 1, 5, 9, 13, 17 or 21; for i2c1, SDA is on GPIO 2, 6, 10, 14, 18 or 26 and SCL on GPIO 3, 7, 11, 15, 19 or 27. Check the GPIO function table in the datasheet for your choice. The Pico board header in the SDK defaults to i2c0 with SDA on GPIO 4 and SCL on GPIO 5.

SignalPico pin used here
SDAGPIO 4 (physical pin 6)
SCLGPIO 5 (physical pin 7)
3V3physical pin 36
GNDphysical pin 38

The TMP102 runs from 1.4 V to 3.6 V and has its address selected by the ADD0 pin: tied to ground the 7-bit address is 0x48, to V+ it is 0x49, to SDA 0x4A and to SCL 0x4B. Use ADD0 to ground for 0x48.

Initialize the controller

i2c_setup.cc
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"

#define I2C_PORT i2c0
#define SDA_PIN  4
#define SCL_PIN  5

void i2c_setup(void)
{
    uint actual = i2c_init(I2C_PORT, 400 * 1000);
    printf("i2c baud: %u\n", actual);

    gpio_set_function(SDA_PIN, GPIO_FUNC_I2C);
    gpio_set_function(SCL_PIN, GPIO_FUNC_I2C);
    gpio_pull_up(SDA_PIN);
    gpio_pull_up(SCL_PIN);
}

i2c_init(i2c, baudrate) releases the controller from reset, programs the clock timing and enables it in master mode, returning the baud rate it actually set. gpio_set_function(pin, GPIO_FUNC_I2C) connects the pins to the controller. The two gpio_pull_up calls enable the RP2040's internal pull-ups, which are about 50 to 80 kilohms and too weak to meet the rise time at 400 kHz on anything but a very short bus. They are worth enabling when the sensor board has no pull-ups of its own, since they keep the lines defined, but for reliable operation use external resistors of 2.2 to 4.7 kilohms (many sensor boards, including most TMP102 breakouts, already carry them).

With clk_sys at 125 MHz the SDK computes the counts so the actual rate is close to 400 kHz:

Text
i2c baud: 400000

The returned number may be slightly different, such as 396825, depending on the divider rounding.

The sensor's registers

The TMP102 has four registers selected by a one-byte pointer register: temperature (0x00), configuration (0x01), and the low and high limits (0x02, 0x03). The temperature register is 16 bits, sent high byte first, with a 12-bit value left-justified in it. Each count is 0.0625 degrees Celsius, and the low four bits are zero in 12-bit mode. The conversion is:

Text
temperature = ((byte0 << 8 | byte1) >> 4) * 0.0625   (sign-extended)

For example, bytes 0x19 0x00 give 0x1900 >> 4 = 0x190 = 400, and 400 * 0.0625 = 25.0 degrees. A negative temperature has bit 11 set in the 12-bit value and needs sign extension: bytes 0xE7 0x00 give 0xE70 (3696), which is 3696 - 4096 = -400 counts, or -25.0 degrees.

The register read

A register read has two steps: write the pointer, then read the two bytes. i2c_write_blocking takes a final argument, nostop, that when true leaves the bus owned after the write, so the next call begins with a repeated start instead of a stop followed by a start:

tmp102.cc
#include "hardware/i2c.h"

#define TMP102_ADDR 0x48
#define TMP102_REG_TEMP 0x00

int tmp102_read_temp(float *celsius)
{
    uint8_t reg = TMP102_REG_TEMP;
    uint8_t raw[2];

    int w = i2c_write_blocking(I2C_PORT, TMP102_ADDR, &reg, 1, true);   /* nostop = true */
    if (w < 0) {
        return w;                                  /* PICO_ERROR_GENERIC: no ACK */
    }
    int r = i2c_read_blocking(I2C_PORT, TMP102_ADDR, raw, 2, false);
    if (r < 0) {
        return r;
    }

    int16_t value = (int16_t)((raw[0] << 8) | raw[1]) >> 4;   /* arithmetic shift keeps the sign */
    *celsius = value * 0.0625f;
    return 0;
}

int main(void)
{
    stdio_init_all();
    i2c_setup();

    while (true) {
        float c;
        if (tmp102_read_temp(&c) == 0) {
            printf("temperature = %.2f C\n", c);
        } else {
            printf("read failed\n");
        }
        sleep_ms(1000);
    }
}
Text
temperature = 24.94 C
temperature = 24.94 C
temperature = 25.00 C

The functions return the number of bytes transferred, or a negative error. PICO_ERROR_GENERIC (-1) means the address was not acknowledged or another bus error occurred. The conversion casts the 16-bit combination to a signed int16_t before shifting right by 4, which sign-extends on the Cortex-M0+ (arithmetic shift of a signed value). The value 24.94 is 399 * 0.0625; your reading will differ.

The last argument of i2c_read_blocking is nostop; passing false sends a STOP after the last byte. The SDK handles the NACK on the final byte internally.

Writing a register

To change the sensor's configuration, write the pointer and the data bytes in one transaction. The TMP102 configuration register is 16 bits. Setting extended-mode and conversion-rate bits is device specific, so as an example we write the default of 0x60A0 back:

tmp102_cfg.cc
int tmp102_write_config(uint16_t cfg)
{
    uint8_t buf[3] = { 0x01, (uint8_t)(cfg >> 8), (uint8_t)cfg };
    int w = i2c_write_blocking(I2C_PORT, TMP102_ADDR, buf, 3, false);
    return (w == 3) ? 0 : -1;
}

The three bytes are the pointer value 0x01 and the two data bytes, all in one write with a stop at the end, which is how the TMP102 expects a register write.

Detecting the device and handling errors

A missing sensor returns an error immediately because the address is not acknowledged. To scan, try a zero-length probe; the SDK idiom is to read one byte and check the return:

scan.cc
void i2c_scan(void)
{
    for (uint8_t addr = 0x08; addr <= 0x77; addr++) {
        uint8_t dummy;
        int ret = i2c_read_timeout_us(I2C_PORT, addr, &dummy, 1, false, 5000);
        if (ret >= 0) {
            printf("device at 0x%02X\n", addr);
        }
    }
}
Text
device at 0x48

i2c_read_timeout_us and i2c_write_timeout_us take a timeout in microseconds, returning PICO_ERROR_TIMEOUT (-2) if a slave stretches the clock beyond it. They are the right choice for any bus where a device might hang, since the plain blocking calls can wait forever for a slave holding SCL low. The SDK rejects reserved addresses (those below 0x08 and above 0x77) with an error, so scan from 0x08.

Pitfalls

  • **Forgetting nostop.** With nostop = false on the write, the bus is released, and the read starts a new transaction; the TMP102 then returns the register selected by its pointer, which happens to still be right, but devices that need the repeated start return stale data. Always use true for the write half of a register read.

  • Wrong address form. The SDK takes the 7-bit address. Passing 0x90 (the write byte) fails.

  • Pull-ups. If transfers fail intermittently at 400 kHz, drop to 100 kHz in i2c_init to test, then fix the pull-ups.

  • Pins not routed to I2C. An SDA pin that is not on the right function row returns errors; check the datasheet table.

  • Using the wrong block. i2c0 and i2c1 have different pin sets.

  • Floating a conversion. value * 0.0625f multiplies by a power of two, so it is exact in floating point; there is no rounding surprise.

When the SDK calls are not enough

The blocking calls tie up the CPU for the transaction: about 0.2 milliseconds for a short register read at 400 kHz. For frequent reads, the controller's FIFO and DMA support let you queue a transfer and continue, but the SDK exposes that only through lower-level functions. A bus with multiple tasks on both cores needs a mutex around the I2C calls, because two cores interleaving transactions corrupt each other. And a device that needs clock stretching beyond the timeout needs the timeout version of the calls with a larger value.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.