【PlatformIO】基于Arduino的ESP8266 锂电池电压、电量测试
效果展示
整体架构流程
估算电量百分比
电池电压与剩余电量的关系因电池类型而异。以2节锂电池(3.7V 标称) 为例:
1.满电电压:8.4V
2.空电电压:6.4V(低于此可能损坏电池)
ESP8266的模拟接口输出值范围为0到1023。ESP8266只有一个模拟输入输出引脚,即A0,其读取的模拟值为0到1.0V。
电路设计
分压电路:由于 ESP8266 的 ADC 输入电压范围是 0-1V(部分开发板扩展为 0-3.3V),需通过电阻分压将电池电压降低到安全范围。
VADC = VBAT × R2 / (R1+R2)
代码展示
#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
// 分压器比例(输入电压到 ADC 电压的比例)
const float voltageDividerRatio = 8.4; // 分压比(8.4倍缩小)
// 电压范围(电池电压)
const float minVoltage = 6.4; // 电压为0%时
const float maxVoltage = 8.4; // 电压为100%时
// 采样次数
const int numSamples = 10;
float batteryVoltage = 0; // 计算电池电压
int batteryPercentage = 0;
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display
void u8g2Show(float hum,float tem){
u8g2.clearBuffer(); // clear the internal memory
u8g2.enableUTF8Print();//enable UTF8
u8g2.setFont(u8g2_font_wqy12_t_gb2312b);//设置中文字符集
u8g2.setCursor(0, 10);
u8g2.print("电压: V");
u8g2.setCursor(40, 10);
u8g2.print(hum);
u8g2.setCursor(0, 30);
u8g2.print("电量: %");
u8g2.setCursor(40, 30);
u8g2.print(tem);
u8g2.sendBuffer(); // transfer internal memory to the display
}
// 对 ADC 数据多次采样并计算平均值
float getAverageAdcVoltage()
{
long totalAdcValue = 0;
// 多次采样
for (int i = 0; i < numSamples; i++)
{
totalAdcValue += analogRead(A0); // 读取 ADC 数据
delay(10); // 每次采样间隔 10ms
}
// 计算平均 ADC 值
float averageAdcValue = totalAdcValue / (float)numSamples;
// 将 ADC 值转换为电压
return (averageAdcValue / 1023.0) * 1.0; // ESP8266 的参考电压为 1.0V
}
// 计算电池电量百分比的函数
int mapBatteryPercentage(float voltage)
{
if (voltage <= minVoltage)
return 0; // 小于等于最小电压时,电量为 0%
if (voltage >= maxVoltage)
return 100; // 大于等于最大电压时,电量为 100%
// 根据线性比例计算电量百分比
return (int)((voltage - minVoltage) / (maxVoltage - minVoltage) * 100);
}
void setup() {
// put your setup code here, to run once:
//dht.begin();//开始测量
u8g2.begin();
}
void loop() {
// put your main code here, to run repeatedly:
// 对 ADC 数据多次采样并求平均
float adcVoltage = getAverageAdcVoltage();
// 将采样的 ADC 电压转换为实际电池电压
batteryVoltage = adcVoltage * voltageDividerRatio; // 计算电池电压
// 根据电池电压计算电量百分比
batteryPercentage = mapBatteryPercentage(batteryVoltage);
u8g2Show(batteryVoltage,batteryPercentage);
delay(2000);//2s测量一次
}
视频展示
【PlatformIO】基于Arduino的ESP8266 锂电池电压、电量测试