Serial output actual voltage through divider

Method to convert raw analog data back into voltage and then convert back to actual voltage before divider.


/* This sketch serial outputs a voltage through a voltage divider into

  analog pin 0

This is written in as simple terms as possible, so its long.

  Actual real numbers math is only 3 lines of code so
  skip to the code if you understand voltage dividers.

Resistance divider follows Vout = Vin * (R2 / (R1 + R2))

  This sketch is assuming 25V max is measured.
  Resistance values used for 1/5 divider are R1 = 10k and R2 = 2.5K

BEFORE YOU CONNECT voltage divider to arduino, test with a meter to verify.

  If you connect 25Vdc to arduino... its bad.  

Meter Black Lead to Gnd

  Gnd -- R2 -- Meter Red Lead -- R1 -- V+ (measured voltage 0-25Vdc)

Connection: Gnd -- R2 -- arduino pin A0 -- R1 -- V+ (measured voltage 0-25Vdc)

I can get to within 0.05 Vdc by measuring actual value of resistors


//Analog volt read pin

const int voltPin = 0;

//Variables for voltage divider

float denominator;

int resistor1 = 10000;

int resistor2 = 2500;

void setup() {

  //Convert resistor values to division value
  //  Equation is previously mentions voltage divider equation
  //  R2 / (R1 + R2)
  //  In this case returns 0.20 or 1/5
  denominator = (float)resistor2 / (resistor1 + resistor2);

} // Void Setup Close

void loop() {

  float voltage;
  //Obtain RAW voltage data
  voltage = analogRead(voltPin);

  //Convert to actual voltage (0 - 5 Vdc)
  voltage = (voltage / 1024) * 5.0;

  //Convert to voltage before divider
  //  Divide by divider = multiply
  //  Divide by 1/5 = multiply by 5
  voltage = voltage / denominator;

  //Output to serial
  Serial.print("Volts: ");

  //Delay to make serial out readable

} // void loop close