文号D890651
733
0
收藏
编辑文章

电量测量程序

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)

[修改于 2年2个月前 - 2024/08/12 11:32:44]

0
还没有人评论哦~~

想参与大家的讨论?现在就 登录 或者 注册。

WEIZHANGLI
机友
文章
2
回复
15
学术分
-2
2024/06/16注册,1年2个月前活动

一名初中生

主体类型:个人
所属领域:无
认证方式:手机号
IP归属地:浙江
ID: {{ user.uid }}
投诉或举报
加载中...
{{ tip }}
请选择违规类型:
{{ reason.type }}

空空如也

加载中...
回复
设为精选取消精选
评学术分
鼓励
编辑
查看历史
通过审核
移动文章
加入收藏取消收藏
退修或删除
违规记录
投诉或举报
加入黑名单移除黑名单
查看IP
{{ format('YYYY/MM/DD HH:mm:ss', toc) }}
回复
加入收藏取消收藏