Simvik

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, return false. Otherwise set ADC_CR_START in CR, remember that it is busy and when it started, and return true.
  • adc_poll(d, now, &value):
  • not busy: return ADC_NOT_STARTED;
  • EOC set in SR: clear EOC, store DR in value, stop being busy, return ADC_DONE;
  • otherwise, if timeout ticks or more have passed since the start: stop being busy and return ADC_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 idle

A 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 7

Learn it first

More Driver design: HAL versus bare metal problems