Simvik

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) sends n bytes (0 to 255) to the device at the 7-bit address addr. Program CR2 with the address, NBYTES, AUTOEND and START in one write. Before each byte, wait for TXIS; if NACKF is set instead, nobody answered: stop sending. Either way, wait for STOPF, clear STOPF and NACKF in ICR, and return -1 after a NACK or 0 otherwise.
  • eeprom_write_byte(mem, value) writes one byte at memory address mem, 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]
AB

Learn it first

  • I2C · Addressing, repeated start, clock stretching and bus recovery.

More I2C problems