简体   繁体   中英

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.

I am using Arduino to measure the voltage of simple 1.5V battery.
So I see that serial monitor shows 1V voltage instead of 1.5V (but the voltmeter shows 1.5V from the battery).
And when I serially connect 2 batteries the serial monitor shows 3V.

Can someone please explain what is going on.

This is my Arduino code:

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).
For 2 serially connected batteries shows 3V, which is correct.

The map function only operates with the long type, meaning it accepts long arguments and it returns a 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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