一、如下nRF54L15 使用 Zephyr API 和 nrfx 驱动初始化 ADC 采集电压
需要注意的地方 - IO需要芯片指定的AIN引脚
- 最大分辨率是14bit(采样率:31.25 ksps)
- nRF54L15 的 ADC 内部参考电压(ADC_REF_INTERNAL)为 0.9 V
- 如需采集电压,由于分压电阻不同,需要调整 ADC_ACQ_TIME_DEFAULT如下图
二、Zephyr API 方式
2.1 prj.conf配置prj.conf 配置 2.2 overlay 配置(如:nrf54l15dk_nrf54l15_cpuapp.overlay)&adc { #address-cells = <1>; #size-cells = <0>; status = "okay"; channel@0 { reg = <0>; zephyr,gain = "ADC_GAIN_1_4"; zephyr,reference = "ADC_REF_INTERNAL"; zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>; zephyr,input-positive = <NRF_SAADC_AIN4>; /* P1.11 for the nRF54L15 DK */ zephyr,resolution = <14>; };};2.3 代码示例#include <zephyr/drivers/adc.h>static const struct adc_dt_spec adc_channel = ADC_DT_SPEC_GET(DT_PATH(zephyr_user));void main(void){ int err; int16_t buf; struct adc_sequence sequence = { .buffer = &buf, .buffer_size = sizeof(buf), }; if (!adc_is_ready_dt(&adc_channel)) { printk("ADC not ready\n"); return; } err = adc_channel_setup_dt(&adc_channel); if (err < 0) { printk("ADC channel setup failed: %d\n", err); return; } err = adc_sequence_init_dt(&adc_channel, &sequence); if (err < 0) { printk("ADC sequence init failed: %d\n", err); return; } while (1) { err = adc_read(adc_channel.dev, &sequence); if (err < 0) { printk("ADC read failed: %d\n", err); } else { printk("ADC raw value: %d\n", buf); } k_msleep(1000); }}三、NRFX库方式3.1 prj.conf配置CONFIG_NRFX_SAADC=y3.2 代码示例#include <nrfx_saadc.h>#define NRF_SAADC_INPUT_AIN4 NRF_PIN_PORT_TO_PIN_NUMBER(11U, 1)#define SAADC_INPUT_PIN NRF_SAADC_INPUT_AIN4static nrfx_saadc_channel_t channel = NRFX_SAADC_DEFAULT_CHANNEL_SE(SAADC_INPUT_PIN, 0);static int16_t sample;void main(void){ nrfx_err_t err; err = nrfx_saadc_init(1); // 1为优先级,可根据实际调整 if (err != NRFX_SUCCESS) { printk("SAADC init error: %08x\n", err); return; } channel.channel_config.gain = NRF_SAADC_GAIN1_4; err = nrfx_saadc_channels_config(&channel, 1); if (err != NRFX_SUCCESS) { printk("SAADC channel config error: %08x\n", err); return; } while (1) { err = nrfx_saadc_buffer_set(&sample, 1); if (err != NRFX_SUCCESS) { printk("SAADC buffer set error: %08x\n", err); return; } err = nrfx_saadc_mode_trigger(); if (err != NRFX_SUCCESS) { printk("SAADC trigger error: %08x\n", err); return; } printk("SAADC sample: %d\n", sample); k_msleep(1000); }}如需采集电压值(单位 mV),可用如下公式换算
int battery_voltage = ((900*4) * sample) / ((1<<12)); // 12位分辨率
|