Scan the multiplexer channels
Convert each enabled ADC channel in turn from the conversion-complete interrupt. A medium embedded C problem (ADC), run and graded in the browser.
medium · ADC · adc · interrupts · multiplexer
A microcontroller has one ADC behind a multiplexer: it converts one channel at a time. Firmware scans several by switching the multiplexer in the conversion-complete interrupt.
scan_start(s)selects the lowest enabled channel and returns it, or returns 0xFF if no channel is enabled.scan_done(s, result)storesresultfor the channel just converted, moves on to the next enabled channel (wrapping from 7 back to 0), and returns it.
Starter code
uint8_t scan_start(scan_t *s) {
s->current = 0;
return 0;
}
uint8_t scan_done(scan_t *s, uint16_t result) {
s->value[s->current] = result;
s->current++;
return s->current;
}Example tests
Channels 0, 1 and 3
scan_t s = { 0x0B };
run(&s, 5);Expected output:
0 1 3 0 1 3Results land in the right channel
scan_t s = { 0x05 };
run(&s, 3);
printf("%u %u\n", s.value[0], s.value[2]);Expected output:
0 2 0 2
300 200Learn it first
- ADC · Resolution, sampling, noise, oversampling and DMA.
More ADC problems
- Median of five samples · Reject a single spike by taking the median instead of the average.
- Oversample for extra bits · Gain resolution from a noisy ADC by summing and shifting.
- Compensate for the supply voltage · Convert a reading to millivolts using the internal reference instead of an assumed 3.3 V.
- Detect an open or shorted sensor · Report a sensor fault when readings sit at a rail for three samples in a row.
- Fix: a random battery voltage at power-up · An average starts from whatever was in memory.
- Greenhouse: calibrated soil moisture · Turn a soil probe reading into a percentage using the probe's own calibration.