const int adcPin = A0; // 使用A0引脚作为ADC输入
const float voltageDividerRatio = 2.0; // 分压比
const float referenceVoltage = 5.0; // Arduino Nano的参考电压(通常为5V)
const int adcMaxValue = 1023; // 10位ADC的最大值
const float maxBatteryVoltage = 9.0; // 电池满电时的电压
const float minBatteryVoltage = 6.0; // 电池没电时的电压
void setup() {
Serial.begin(9600);
}
void loop() {
int adcValue = analogRead(adcPin); // 读取ADC值
float measuredVoltage = (adcValue * (referenceVoltage / adcMaxValue)); // 分压后的电压
float actualVoltage = measuredVoltage * voltageDividerRatio; // 计算实际电池电压
float batteryPercentage = calculateBatteryPercentage(actualVoltage); // 计算电池电量百分比
Serial.print("Battery Voltage: ");
Serial.print(actualVoltage);
Serial.println(" V");
Serial.print("Battery Percentage: ");
Serial.print(batteryPercentage);
Serial.println(" %");
delay(1000); // 每秒输出一次
}
// 计算电量百分比的函数
float calculateBatteryPercentage(float voltage) {
if (voltage >= maxBatteryVoltage) {
return 100.0; // 如果电压大于或等于满电压,电量为100%
} else if (voltage <= minBatteryVoltage) {
return 0.0; // 如果电压小于或等于最低电压,电量为0%
} else {
// 线性比例计算百分比
return ((voltage - minBatteryVoltage) / (maxBatteryVoltage - minBatteryVoltage)) * 100.0;
}
}连接方式+9V (电池正极) | R1 (10kΩ) | ----> A0 (Arduino Nano) | R2 (10kΩ) | GND (电池负极 和 Arduino Nano的GND)