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. A hard embedded C problem (I2C), run and graded in…
hard · I2C · driver · registers · i2c · eeprom · nack
I2C1 is simulated like the I2C block of an STM32 G0 or L4, with a 24C02 EEPROM at address 0x50. i2c_init under Provided has already set the timing and enabled it. Every transfer shows up in the output when it ends, such as i2c1: write 0x50 [0x10 0x41], or i2c1: 0x50 nack when no device answers.
i2c_write(addr, data, n)sendsnbytes (0 to 255) to the device at the 7-bit addressaddr. ProgramCR2with the address,NBYTES,AUTOENDandSTARTin one write. Before each byte, wait forTXIS; ifNACKFis set instead, nobody answered: stop sending. Either way, wait forSTOPF, clearSTOPFandNACKFinICR, and return -1 after a NACK or 0 otherwise.eeprom_write_byte(mem, value)writes one byte at memory addressmem, then waits until the EEPROM has finished storing it. A 24C02 takes up to 5 ms and ignores its address meanwhile, so poll it: send empty writes (n= 0) until one is acknowledged, at most 100 times. Return 0 when the write is done, -1 if a write or the polling failed.
Starter code
int i2c_write(uint8_t addr, const uint8_t *data, int n) {
return -1;
}
int eeprom_write_byte(uint8_t mem, uint8_t value) {
return -1;
}Example tests
Write two bytes and read them back
i2c_init();
printf("%d\n", eeprom_write_byte(0x10, 'A'));
printf("%d\n", eeprom_write_byte(0x11, 'B'));
uint8_t out[2];
eeprom_read(0x10, out, 2);
printf("%c%c\n", out[0], out[1]);Expected output:
i2c1: write 0x50 [0x10 0x41]
i2c1: 0x50 nack
i2c1: write 0x50 []
0
i2c1: write 0x50 [0x11 0x42]
i2c1: 0x50 nack
i2c1: write 0x50 []
0
i2c1: write 0x50 [0x10]
i2c1: read 0x50 [0x41 0x42]
ABLearn it first
- I2C · Addressing, repeated start, clock stretching and bus recovery.
More I2C problems
- Scan the bus · Find every device on the bus without probing the reserved addresses.
- 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: 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.