简体   繁体   English

Arduino显示1.5V电池电压错误

[英]Arduino shows wrong voltage for 1.5V battery

I am seeing strange behavioral, now want to understand if this is something connected with Arduino UNO or with my code. 我看到了奇怪的行为,现在想了解这是否与Arduino UNO或我的代码有关。

I am using Arduino to measure the voltage of simple 1.5V battery. 我正在使用Arduino测量简单的1.5V电池的电压。
So I see that serial monitor shows 1V voltage instead of 1.5V (but the voltmeter shows 1.5V from the battery). 所以我看到串行监视器显示的是1V电压而不是1.5V(但是电压表显示的是电池的1.5V)。
And when I serially connect 2 batteries the serial monitor shows 3V. 当我串行连接2块电池时,串行监视器显示3V。

Can someone please explain what is going on. 有人可以解释发生了什么吗?

This is my Arduino code: 这是我的Arduino代码:

float voltage;
float batteryIn;

void setup(){
    Serial.begin(9600);
}

void loop(){

    batteryIn = analogRead(0);
    float voltage2 =  (float)map(batteryIn, 0, 1023, 0, 5); 
    Serial.println(voltage2);
    delay(50);
}

So shows 1V for single battery ( but should be 1.5V). 因此对于单节电池显示1V(但应为1.5V)。
For 2 serially connected batteries shows 3V, which is correct. 对于2个串联的电池,显示3V,这是正确的。

The map function only operates with the long type, meaning it accepts long arguments and it returns a long . map函数仅使用long类型进行操作,这意味着它接受long参数并返回long
Casting an integer to floating point value, won't make it magically have decimal values. 将整数转换为浮点值,将不会使其神奇地具有十进制值。

You need to implement a map function that operates with floats. 您需要实现一个使用浮点数的map函数。

float mapf(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
float voltage2 = mapf(batteryIn, 0, 1023, 0, 5);

In your case you could also simplify the expression and use it inline. 您还可以简化表达式并内联使用。

float voltage2 = batteryIn * 5.0 / 1023.0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM