Simvik

Fix: the header that broke the build

A second header now includes adc.h, and the build fails twice over. Fix the driver's interface without rewriting it. An easy embedded C problem (Scope,…

easy · Scope, linkage and storage duration · headers · linkage · debugging

Bug report. Since board.h was added, which includes adc.h like main.c already did, the firmware no longer builds. Fixing the first error only brings up a second one, in adc.c.

The driver itself was reviewed and is right: adc_read_mv returns the reading of a 12-bit ADC with a 3.3 V reference, in millivolts. Make the header right for every file that includes it, changing at most five lines.

Starter code

// ===== adc.h =====
// adc.h: the ADC driver's interface.
#include <stdint.h>

typedef enum { ADC_CH_VBAT = 0, ADC_CH_TEMP = 1 } adc_channel_t;

void adc_init(void);
int adc_read_mv(adc_channel_t ch);

// ===== adc.c =====
#include "adc.h"

void adc_init(void) {
  ADC_CTRL = 1u;   // enable
}

uint16_t adc_read_mv(adc_channel_t ch) {
  uint32_t raw = ADC_DATA[ch];
  return (uint16_t)((raw * 3300u + 2047u) / 4095u);
}

Example tests

Full scale and half scale

ADC_DATA[0] = 4095u;
ADC_DATA[1] = 2048u;
adc_init();
printf("%u %u %u\n", (unsigned)ADC_CTRL, (unsigned)adc_read_mv(ADC_CH_VBAT), (unsigned)adc_read_mv(ADC_CH_TEMP));

Expected output:

1 3300 1650

Learn it first

More Scope, linkage and storage duration problems