Simvik

A fake I2C device for driver tests

Write a fake I2C bus with one register-mapped device, so a sensor driver can be tested on a PC. A medium embedded C problem (Testing and code coverage), run…

medium · Testing and code coverage · testing · fakes · i2c · drivers

Write i2c_write_read as a fake of a typical register-mapped sensor at address FAKE_ADDR, with 256 registers in fake_regs:

  • Count every call in fake_transactions. Return -1 if addr is not FAKE_ADDR or fake_present is false.
  • If ntx > 0, the first byte sets the device's register pointer. Any further bytes are written to the registers from the pointer on, and the pointer moves up one per byte.
  • Then read nrx bytes from the pointer on, moving it up one per byte. With ntx == 0, reading continues from where the pointer was left.
  • The pointer wraps from 0xFF to 0x00.

The tests run a small IMU driver against your fake.

Starter code

int i2c_write_read(uint8_t addr, const uint8_t *tx, int ntx, uint8_t *rx, int nrx) {
  (void)addr; (void)tx; (void)ntx;
  for (int i = 0; i < nrx; i++) rx[i] = 0;
  return 0;
}

Example tests

WHO_AM_I and an accelerometer reading

fake_regs[0x75] = 0x68;
uint8_t raw[6] = { 0x40, 0x00, 0xFF, 0x38, 0x00, 0x10 };
memcpy(&fake_regs[0x3B], raw, 6);
printf("who am i: 0x%02X\n", imu_whoami());
accel();
printf("%d transactions\n", fake_transactions);

Expected output:

who am i: 0x68
accel: 16384 -200 16
2 transactions

Learn it first

More Testing and code coverage problems

  • Test with a fake GPIO · Write a fake that records pin writes and delays, so code can be tested off target.
  • Write a CMock-style mock · A mock that checks a driver makes exactly the bus writes a test expects, in order, and reports what went wrong.
  • Write tests that catch the bugs · Write a test suite for a scaling function. It is graded by running it against buggy versions it must reject.