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:
0x00011234Low 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:
0x00020005Learn 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
- Drive a GPIO pin · Set or clear one pin in a port's output data register.
- Read a GPIO pin · Report the level on one input pin.
- Configure a pin mode · Write a 2-bit mode field for one pin of a port.
- Atomic pin write · Change a pin with a single write to the bit set/reset register.
- Hygienic register macros · Fix four bit-manipulation macros that break on compound arguments.
- Clear a write-1-to-clear flag · Acknowledge one interrupt flag without wiping the others.
- Poll with a timeout · Wait for a status bit, but never forever.
- UART baud-rate divisor · Compute the divisor that gives the closest baud rate.
- PWM compare value · Convert a duty cycle in percent to a timer compare value.
- Lay out a register map · Declare a peripheral struct whose members land on the right offsets.
- ADC conversion sequence · Write a 5-bit channel number into a computed slot of a register.
- Fix: disabling one interrupt silences the timers · Clearing one bit of an interrupt-enable register clears every bit below it as well.
- Infusion pump: read the pressure, with a timeout · Start a conversion, poll its done flag, and give up safely if the converter never answers.