I am trying to measure the battery voltage on my custom board which is based on the nRF52832 device. I am using nRF Connect SDK 2.7.0 in VS Code. The dts file for this custom board contains (among other things that aren't germane to this question):
/ { model = "rwe_152001_01_nrf52832"; compatible = "rwe,rwe_152001_01_nrf52832"; zephyr,user { io-channels = <&adc 7>; // Use channel 0 for VDD measurement }; }; &adc { status = "okay"; };
My code is as follows and I have tried various channels (0, 4, and 7 at the 'suggestion" of Copilot), but I keep getting " <err> adc_nrfx_saadc: Channel 7 not configured
ADC read failed: -22" in the console. I think I am close but I just can't seem to figure it out. Please forgive my newbiness.
ADC read failed: -22" in the console. I think I am close but I just can't seem to figure it out. Please forgive my newbiness.
#pragma GCC diagnostic ignored "-Wmain" #include <zephyr/kernel.h> #include <zephyr/device.h> #include <zephyr/drivers/adc.h> #include <zephyr/devicetree/io-channels.h> #include <stdio.h> #define ADC_RESOLUTION 10 #define ADC_GAIN ADC_GAIN_1_6 #define ADC_REFERENCE ADC_REF_INTERNAL #define ADC_ACQUISITION_TIME ADC_ACQ_TIME_DEFAULT static const struct adc_dt_spec adc_spec = ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 0); static int16_t sample_buffer; void main(void) { int err; printk("a\n"); if (!device_is_ready(adc_spec.dev)) { printk("ADC device not found\n"); return; } printk("b\n"); struct adc_channel_cfg channel_cfg = { .gain = ADC_GAIN, .reference = ADC_REFERENCE, .acquisition_time = ADC_ACQ_TIME_DEFAULT, .channel_id = adc_spec.channel_id, }; err = adc_channel_setup(adc_spec.dev, &channel_cfg); printk("c\n"); if (err) { printk("ADC channel setup failed: %d\n", err); return; } const struct adc_sequence sequence = { .channels = BIT(adc_spec.channel_id), .buffer = &sample_buffer, .buffer_size = sizeof(sample_buffer), .resolution = ADC_RESOLUTION, }; while (1) { err = adc_read(adc_spec.dev, &sequence); if (err) { printk("ADC read failed: %d\n", err); } else { // Convert the raw sample to voltage //float voltage = (sample_buffer * 3.6) / 1024; // Assuming 3.6V reference and 10-bit resolution //char voltage_str; printk("ADC sample: %d\n", sample_buffer); } k_sleep(K_MSEC(1000)); } }