I created this simple project to measure a DC voltage using an Arduino Mega. The circuit diagram is as follows:
The power jack supplies 9 V ideally. With my multimeter, I measured it to be 10.16 V.
The code for measuring the voltage is:
#include <Wire.h>
#include <hd44780.h> // main hd44780 header
#include <hd44780ioClass/hd44780_I2Cexp.h> // i2c expander i/o class header
hd44780_I2Cexp lcd;
const int LCD_COLS = 16;
const int LCD_ROWS = 2;
const float R1 = 4.55 + 0.099; // ideally 4.8 kohm
const float R2 = 1.166; // ideally 1.2 kohm
void setup() {
lcd.begin(LCD_COLS, LCD_ROWS);
lcd.setCursor(0, 0);
lcd.print("Voltage: ");
lcd.setCursor(0, 1);
}
void loop(){
float reading = (analogRead(A0) * 4.9) / 1000;
float voltage = (reading * (R1 + R2)) / R2;
lcd.setCursor(0, 1);
lcd.print(voltage);
lcd.print("V");
delay(5000);
}
To get an accurate reading, I replaced the resistance values in the code with what I measured using the multimeter.
But, as you can see below, there is still a difference of around 2 V.
Any idea how I can rectify this?

