I am trying to get a very simple ADC reading to print to the console using the nRF5340DK. I have a voltage divider with a photoresistor and a regular resistor, and I am trying to pass the output voltage as an analog input to P0.04. I am using nRF Connect in VSCode, version v2023.4.179. I am using the onboard VDD (3V) and GND for the circuit. I have enabled ADC in the prj.conf file. I will attach my main.c file to this. When I build and flash the code to the board, I get error -22 from adc_read. I would greatly appreciate any advice to solve this issue. Thank you!
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <zephyr/sys/util.h>
#define INPUT_PIN 0
#define ADC_NODE DT_NODELABEL(adc)
static const struct device * dev = DEVICE_DT_GET(ADC_NODE);
#define ADC_RESOLUTION 10
#define ADC_GAIN ADC_GAIN_1
#define ADC_REFERENCE ADC_REF_INTERNAL
#define ADC_ACQUISITION_TIME ADC_ACQ_TIME_DEFAULT
#define ADC_CHANNEL 0
#define ADC_PORT SAADC_CH_PSELN_PSELN_AnalogInput0
struct adc_channel_cfg chl_cfg = {
.gain = ADC_GAIN,
.reference = ADC_REFERENCE,
.acquisition_time = ADC_ACQUISITION_TIME,
.channel_id = ADC_CHANNEL,
#ifdef CONFIG_ADC_NFRX_SAADC
.input_positive = ADC_PORT
#endif
};
int16_t sample_buffer[1];
struct adc_sequence seq = {
.channels = BIT(ADC_CHANNEL),
.buffer = sample_buffer,
.buffer = sizeof(sample_buffer),
.resolution = ADC_RESOLUTION
};
void main(void) {
int err;
if (!device_is_ready(dev)) {
printk("device not ready\n");
return;
}
err = adc_channel_setup(dev, &chl_cfg);
if (err != 0) {
printk("channel setup failed\n");
return;
}
while (1) {
err = adc_read(dev, &seq);
if (err != 0) {
printk("read failed %d \n", err);
return;
}
int32_t mv_value = sample_buffer[0];
int32_t adc_vref = adc_ref_internal(dev);
adc_raw_to_millivolts(adc_vref, ADC_GAIN, ADC_RESOLUTION, &mv_value);
printk("ADC-voltage: %d mV\n", mv_value);
// sleep for half a second
k_msleep(500);
}
}