Scan the bus
Find every device on the bus without probing the reserved addresses. An easy embedded C problem (I2C), run and graded in the browser.
easy · I2C · i2c · bring-up
The first thing to run on a new board is a bus scan: address every possible device and list the ones that answer.
Write i2c_scan(found, max): call i2c_probe() for every valid 7-bit address, store the ones that answer in found in increasing order (at most max of them), and return how many were stored.
Addresses 0x00 to 0x07 and 0x78 to 0x7F are reserved (general call, 10-bit addressing, high-speed mode codes) and must not be probed: scan 0x08 to 0x77.
Starter code
int i2c_scan(uint8_t *found, int max) {
int n = 0;
for (int addr = 0; addr < 128; addr++) {
if (i2c_probe((uint8_t)addr)) found[n++] = (uint8_t)addr;
}
return n;
}Example tests
An OLED and a clock
show();Expected output:
2 found: 0x3C 0x68 (112 probes)Learn it first
- I2C · Addressing, repeated start, clock stretching and bus recovery.
More I2C problems
- Read a 16-bit register · Write the register pointer, read two bytes back with a repeated start, and handle a NACK.
- Recover a stuck bus · Clock a stuck device out with up to nine pulses, then send a STOP.
- Size the pull-up resistors · Work out the smallest and largest pull-up that meet the I2C specification.
- Driver: write an EEPROM over I2C, with ACK polling · Send an I2C write with the hardware's byte-by-byte handshake, then poll until the EEPROM finishes writing.
- Driver: read registers with a repeated start · Write a register address, then read bytes back without releasing the bus in between.
- Fix: every second transfer is cut short · A write routine leaves STOPF set, so the next transfer thinks it has already finished.
- HVAC controller: trust the humidity reading · Combine the bytes an I²C humidity sensor returns, check their CRC, and scale them.