Skip to content
systemcoding.dev
Embedded

Read I2C Sensors With TinyGo machine.I2C and the drivers Package

Configure machine.I2C0 in TinyGo, scan the bus, read a chip ID register by hand, then read a BME280 with the tinygo.org/x/drivers package.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Go, Arm and Rust logos.

An I2C sensor is two wires and an address, and TinyGo makes the software side almost as short. The machine package gives you the bus, and the tinygo.org/x/drivers module gives you ready-made drivers for hundreds of chips. This post uses both: it configures I2C on a Raspberry Pi Pico, scans for devices, reads a register by hand to prove the wiring, and then reads temperature, pressure and humidity from a BME280 through the driver. It uses TinyGo 0.37 and assumes you flashed a blinky already, as in the Pico blinky post. It is the same task as reading an I2C sensor from MicroPython, in a typed language, which makes it a useful comparison.

For bus basics, the NXP I2C-bus specification is the authority: two open-drain lines, SDA and SCL, pulled up to the supply voltage, with 7-bit device addresses.

Wire the sensor

A BME280 breakout board has pins for power, ground, SDA and SCL. On the Pico, connect:

Sensor pinPico pinNotes
VIN3V3 (pin 36)Use 3.3 V; many breakouts also accept 5 V, but the Pico's pins are not 5 V tolerant
GNDGNDAny ground pin
SDAGP4 (pin 6)I2C0 SDA
SCLGP5 (pin 7)I2C0 SCL

Most breakout boards carry pull-up resistors on SDA and SCL. If you connect several boards, the pull-ups add in parallel and the bus can become too strongly pulled, so remove or disable extra ones when a scan shows errors. The BME280 answers at address 0x76 or 0x77, selected by a pin on the breakout.

Configure the bus and scan it

scan.gogo
package main

import (
	"machine"
	"time"
)

func main() {
	time.Sleep(2 * time.Second) // let the USB serial port enumerate

	i2c := machine.I2C0
	err := i2c.Configure(machine.I2CConfig{
		Frequency: 400 * machine.KHz,
		SDA:       machine.GPIO4,
		SCL:       machine.GPIO5,
	})
	if err != nil {
		println("configure failed:", err.Error())
		return
	}

	for addr := uint16(0x08); addr < 0x78; addr++ {
		if err := i2c.Tx(addr, nil, nil); err == nil {
			println("found device at 0x", hex(addr))
		}
	}
	println("scan done")
}

func hex(v uint16) string {
	const digits = "0123456789abcdef"
	return string([]byte{digits[v>>4&0xF], digits[v&0xF]})
}

machine.I2C0 is the first I2C controller. Configure sets the clock frequency and the pins. machine.KHz is a constant so that 400 * machine.KHz reads as 400 kHz, the standard fast-mode speed; use 100 kHz when wires are long or the sensor is slow. If a pin pair is not valid for that controller, Configure returns an error, which the code checks and prints.

Tx(addr, w, r) performs a transaction: it writes w to the device and then reads len(r) bytes into r. With both slices nil it sends only the address byte, and the device answers with an acknowledge if it is present. The call returns an error if nothing acknowledges, so a nil error means a device exists at that address. The scan skips addresses below 0x08 and above 0x77, which the specification reserves. The helper converts a number to two hex digits by hand, which avoids pulling in fmt and keeps the image small.

Text
found device at 0x76
scan done

If the scan finds nothing, the cause is almost always wiring, a missing pull-up or the wrong pins, and no amount of software changes that. Swap SDA and SCL before anything else.

Read a register by hand

Before trusting a driver, read the chip's identity register. The BME280 returns 0x60 from register 0xD0:

chipid.gogo
package main

import (
	"machine"
	"time"
)

const bme280Addr = 0x76

func main() {
	time.Sleep(2 * time.Second)

	i2c := machine.I2C0
	i2c.Configure(machine.I2CConfig{
		Frequency: 400 * machine.KHz,
		SDA:       machine.GPIO4,
		SCL:       machine.GPIO5,
	})

	id := make([]byte, 1)
	if err := i2c.ReadRegister(bme280Addr, 0xD0, id); err != nil {
		println("read failed:", err.Error())
		return
	}
	println("chip id:", id[0])
}
Text
chip id: 96

ReadRegister(addr, reg, buf) writes the register number and then reads len(buf) bytes, which is the usual pattern for sensors. println prints a byte in decimal, so 0x60 appears as 96. A chip ID of 88 (0x58) means you have a BMP280, which has no humidity sensor, and the BME280 driver would then report meaningless humidity. This single read answers three questions: the bus works, the address is right, and the part is what the label says.

Use the driver

The drivers module is a separate Go module, installed like any dependency:

Shell
go get tinygo.org/x/drivers

The BME280 driver then reads the whole sensor, applying the calibration data that the chip stores internally:

bme.gogo
package main

import (
	"machine"
	"time"

	"tinygo.org/x/drivers/bme280"
)

func main() {
	time.Sleep(2 * time.Second)

	i2c := machine.I2C0
	i2c.Configure(machine.I2CConfig{
		Frequency: 400 * machine.KHz,
		SDA:       machine.GPIO4,
		SCL:       machine.GPIO5,
	})

	sensor := bme280.New(i2c)
	sensor.Configure()
	if !sensor.Connected() {
		println("BME280 not found")
		return
	}

	for {
		t, _ := sensor.ReadTemperature()
		p, _ := sensor.ReadPressure()
		h, _ := sensor.ReadHumidity()
		println("temp mC:", t, "pressure mPa:", p, "humidity 0.01%:", h)
		time.Sleep(2 * time.Second)
	}
}
Text
temp mC: 23450 pressure mPa: 101325000 humidity 0.01%: 4520

The values are an example and will differ with your room. The driver returns integers in fixed units so that it needs no floating point: temperature in milli-degrees Celsius, pressure in milli-pascals, and humidity in hundredths of a percent. A reading of 23,450 means 23.45 degrees Celsius, and 101,325,000 milli-pascals is 101,325 Pa, standard atmospheric pressure. The check the driver documents for each version is worth reading in its source, since unit conventions are a matter of the driver and not of I2C.

bme280.New(i2c) takes the bus object. The bus is passed in, which is what lets one driver work on every board TinyGo supports: the driver imports no board-specific code.

Handle errors and share the bus

Every read returns an error, and the example ignores it for brevity. A real program checks it, because a loose wire shows up as a failed transaction, not a wrong number. A common pattern is to retry a few times and then report the failure through an LED or a counter.

I2C devices share a bus, so several drivers can use the same machine.I2C0: construct each driver with the same bus value, and give each a distinct address. TinyGo does not lock the bus between goroutines on its own. If two goroutines use it, protect it with a sync.Mutex, or give the bus to a single goroutine and talk to it through a channel.

Recover from a stuck bus

I2C has one failure that code alone rarely fixes: a device holds SDA low in the middle of a byte, usually because the microcontroller was reset while a transfer was in progress. Every later transaction then fails, and a scan finds nothing even though the wiring is correct. Two habits help.

First, make a failed read visible. Wrap reads in a function that returns the error and count consecutive failures, so a bus that was fine yesterday and silent today shows up as a rising counter instead of a frozen display.

Second, know the recovery sequence. The I2C specification describes it: switch SCL to a general-purpose output, toggle it up to nine times until the device releases SDA, send a stop condition, and reconfigure the pins for I2C. In TinyGo that means calling Configure on the two pins as plain outputs and inputs, toggling the clock line with Set(true) and Set(false) and short sleeps, then calling i2c.Configure again. The simplest fix on hardware you control is a power switch for the sensor, because removing power clears every internal state machine.

Also check the supply. A sensor browning out while the radio or a motor draws current resets part-way through a transfer. The software symptom is the same stuck bus, and the fix is a decoupling capacitor near the sensor.

What differs across boards

The pin numbers and controller names change, and the code does not. On an Arduino Nano RP2040 Connect or a Feather, the board file defines machine.SDA_PIN and machine.SCL_PIN constants, and machine.I2C0 is preconfigured with default pins, so i2c.Configure(machine.I2CConfig{}) with no fields works. Read the board's page in the TinyGo documentation for its defaults.

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.