A non-blocking driver
Start a conversion and poll for it, with a timeout, instead of waiting in a loop. A medium embedded C problem (Driver design: HAL versus bare metal), run and…
medium · Driver design: HAL versus bare metal · driver · non-blocking · state-machine · timeout
The main loop runs many jobs, so a driver must never wait in a loop for hardware. Replace the blocking driver with two calls:
adc_start(d, now): if a conversion is already in progress, returnfalse. Otherwise setADC_CR_STARTinCR, remember that it is busy and when it started, and returntrue.adc_poll(d, now, &value):- not busy: return
ADC_NOT_STARTED; EOCset inSR: clearEOC, storeDRinvalue, stop being busy, returnADC_DONE;- otherwise, if
timeoutticks or more have passed since the start: stop being busy and returnADC_TIMEOUT; - otherwise return
ADC_BUSY.
A result that arrives on the same tick as the timeout counts as done.
Starter code
bool adc_start(adc_drv_t *d, uint32_t now) {
d->regs->CR |= ADC_CR_START;
return true;
}
int adc_poll(adc_drv_t *d, uint32_t now, uint16_t *value) {
while (!(d->regs->SR & ADC_SR_EOC)) {
// wait for the conversion
}
*value = (uint16_t)d->regs->DR;
return ADC_DONE;
}Example tests
One conversion
hw = (fake_adc_t){ .conv_ticks = 3, .sample = 1234 };
adc_drv_t d = { &hw.regs, false, 0, 5 };
printf("%d\n", adc_start(&d, 0));
run(&d, 1, 5);Expected output:
1
t=4 done 1234
t=5 idleA start while busy is refused
hw = (fake_adc_t){ .conv_ticks = 2, .sample = 7 };
adc_drv_t d = { &hw.regs, false, 0, 5 };
printf("%d %d\n", adc_start(&d, 0), adc_start(&d, 0));
run(&d, 1, 3);Expected output:
1 0
t=3 done 7Learn it first
- Driver design: HAL versus bare metal · Layering a driver so it is testable, portable and still fast.
More Driver design: HAL versus bare metal problems
- One interface, two sensors · Put two temperature sensor drivers behind one ops table so the application does not care which chip is fitted.
- Retries, backoff and bus recovery · Decide which bus errors to retry, how long to wait, and when to recover a stuck bus.
- A driver and its interface: led.h and led.c · Split an LED driver into the header the application includes and the source file that keeps the register work to itself.