Simvik

Read a split counter

Read a 32-bit count from two 16-bit halves that keep changing. A hard embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.

hard · Registers and memory-mapped I/O · timers · race-condition

A 32-bit tick count is available only as two 16-bit registers, and it keeps counting while you read them. If the low half rolls over between your two reads, combining them gives a value that is wrong by 65536.

Return a consistent 32-bit value: high << 16 | low, where both halves belong to the same instant.

Starter code

uint32_t timer_read32(void) {
  // The counter may roll over from 0x0001FFFF to 0x00020000 between the two reads.
  uint32_t high = timer_read_high();
  uint32_t low = timer_read_low();
  return (high << 16) | low;
}

Example tests

No rollover during the read

static const uint16_t high[] = { 1, 1, 1, 1, 1, 1 };
static const uint16_t low[] = { 0x1234, 0x1235, 0x1236, 0x1237, 0x1238, 0x1239 };
mock_high = high; mock_low = low;
printf("0x%08X\n", timer_read32());

Expected output:

0x00011234

Low half rolls over mid-read

static const uint16_t high[] = { 1, 2, 2, 2, 2, 2 };
static const uint16_t low[] = { 0x0003, 0x0005, 0x0007, 0x0009, 0x000B, 0x000D };
mock_high = high; mock_low = low;
printf("0x%08X\n", timer_read32());

Expected output:

0x00020005

Learn it first

  • Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

More Registers and memory-mapped I/O problems