Add my_adc/

This commit is contained in:
hangpersonal committed 2026-10-07 22:36:07 -07:00
1 parent ff59d1588c
commit 1deb818d3e
5 files changed
+145

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
#include <inttypes.h>
#include <stdint.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/sys/printk.h>
#define MY_ADC_NODE DT_ALIAS(myadc)
#define MY_ADC_CH_NODE DT_CHILD(MY_ADC_NODE, channel_3)
#define MY_ADC_CHANNEL_ID DT_REG_ADDR(MY_ADC_CH_NODE)
static const struct device *const adc_dev =
DEVICE_DT_GET(MY_ADC_NODE);
static const struct adc_channel_cfg ch_cfg =
ADC_CHANNEL_CFG_DT(MY_ADC_CH_NODE);
static uint16_t sample;
static struct adc_sequence seq = {
.channels = BIT(MY_ADC_CHANNEL_ID),
.buffer = &sample,
.buffer_size = sizeof(sample),
.resolution = DT_PROP_OR(MY_ADC_CH_NODE, zephyr_resolution, 12),
};
int main(void) {
int err;
if (!device_is_ready(adc_dev)) {
printk("ADC device not ready\n");
return 0;
}
err = adc_channel_setup(adc_dev, &ch_cfg);
if (err < 0) {
printk("Could not setup ADC channel (%d)\n", err);
return 0;
}
printk("Reading ADC1 channel 3 on PA3 (Arduino A0)\n");
while (1) {
int32_t val_mv;
sample = 0;
err = adc_read(adc_dev, &seq);
if (err < 0) {
printk("Could not read ADC (%d)\n", err);
k_sleep(K_MSEC(500));
continue;
}
if (ch_cfg.differential) {
val_mv = (int32_t)((int16_t)sample);
} else {
val_mv = (int32_t)sample;
}
printk("ADC raw: %" PRId32, val_mv);
err = adc_raw_to_millivolts(adc_ref_internal(adc_dev), ch_cfg.gain,
seq.resolution, &val_mv);
if (err < 0) {
printk(" (voltage conversion not available)\n");
} else {
printk(" Voltage: %" PRId32 " mV\n", val_mv);
}
k_sleep(K_MSEC(500));
}
return 0;
}