-
在 Arduino环境下,我们如何用高精度ADC检测电压值?
-
支持ADC功能的引脚请查看:引脚定义
1.这里我们就要借助 esp32-hal-adc.h 和 esp32-hal-adc.c 两个文件来完成 esp32-hal库 内置的 ADC 检测功能,分辨率可以设置!
2.下面是 esp32-hal-adc.h 文件,翻译了一下,可以看到各个函数的作用:
#ifndef MAIN_ESP32_HAL_ADC_H_
#define MAIN_ESP32_HAL_ADC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
typedef enum {
ADC_0db,
ADC_2_5db,
ADC_6db,
ADC_11db
} adc_attenuation_t;
/*。
*获取引脚的ADC值。
**/
uint16_t analogRead(uint8_t pin);
/*。
*设置aliogRead返回值的分辨率。默认值为12位(范围从0到4096)
*如果在9和12之间,它将等于设置的硬件分辨率,否则值将移位
*范围为1-16
*注:与Arduino SAM兼容
*/
void analogReadResolution(uint8_t bits);
/*。
*设置采样位和读取分辨率
*默认值为12位(0-4095)
*范围为9-12
*/
void analogSetWidth(uint8_t bits);
/*。
*设置每个样本的周期数
*默认为8,似乎表现不错
*范围为1-255
*/
void analogSetCycles(uint8_t cycles);
/*。
*设置范围内的样本数
*默认值为1
*范围为1-255
*此设置将范围拆分为
*“样本”件,可能看起来
*就像敏感度成倍增长
*那么多次
*/
void analogSetSamples(uint8_t samples);
/*。
*设置ADC时钟的分频器
*默认值为1
*范围为1-255
*/
void analogSetClockDiv(uint8_t clockDiv);
/*
* Set the attenuation for all channels
* Default is 11db
* */
void analogSetAttenuation(adc_attenuation_t attenuation);
/*
*设置所有通道的衰减
*默认值为11db
**/
void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation);
/*。
*获取霍尔传感器的值(不带LNA)
*连接到引脚36(SVP)和39(SVN)
**/
int hallRead();
/*。
*非阻塞接口(差不多)
*
*注:ADC转换一次只能针对单个管脚运行。
*这意味着如果要在同一总线的两个引脚上运行ADC
*需陆续运行。或许最好的用法是。
*在两辆巴士上并行开始转换
**/
/*。
*将引脚连接到ADC(还将清除任何其他可能开启的模拟模式)
**/
bool adcAttachPin(uint8_t pin);
/*
*在连接的引脚总线上开始ADC转换
**/
bool adcStart(uint8_t pin);
/*
*检查引脚的ADC总线上的转换当前是否正在运行
**/
bool adcBusy(uint8_t pin);
/*
*获取转换结果(未完成将等待)
**/
uint16_t adcEnd(uint8_t pin);
#ifdef __cplusplus
}
#endif
#endif /* MAIN_ESP32_HAL_ADC_H_ */
- 自己写的测试代码:
/*
@功能:ADC检测电源电压
@时间:2020/3/6
@作者:刘泽文
@引用库:esp32-hal-adc.h
@QQ:2822604962
*/
#include <Arduino.h>
#define ADC1 15//ADC引脚
void setup(){
Serial.begin(115200);
adcAttachPin(ADC1);//将引脚连接到ADC
adcStart(ADC1);//在连接的引脚总线上开始ADC转换
analogReadResolution(16);//设置aliogRead返回值的分辨率
}
void loop()
{
Serial.print("系统电压是: ");
Serial.print(analogRead(ADC1));
Serial.print(" ");
Serial.print((analogRead(ADC1)*3.3)/65535);
Serial.println(" V");
delay(100);
}