This will show how to use analogRead to get a voltage from an circuit. This circuit is a voltage divider. I have two 1000 Ω resistors in series. It will cut the voltage in half. Without a multimeter it will show you have to display the analog (floating point) voltage. A5 is the analog port that will read the value of the voltage divider. EE: Resistor page shows you how resistors in circuits are calcuated.
analogWrite is 0 to 255 (8 bit). analogRead is 0 to 1024 ( 10 bit). So to convert analogRead into a voltage.
(5. / 1023. ) *analogPort value.
I will put the below code into the Arduino and copy the ino file up after building the circuit.
V_R2 = (5./1023.) * readVal;
The dot after the numbers make the math floating point.
#include <Wire.h>
float V_R2 = 0;
int readVal = 0;
int readPin = A0;
int delayTime = 1000;
void setup() {
Serial.begin(9600);
Wire.begin(0x6); // join i2c bus with address #6
Wire.onReceive(receiveEvent); // register event
pinMode(readPin, INPUT);
}
void loop() {
readVal = analogRead(readPin);
V_R2 = (5./1023.) * readVal;
Serial.println(V_R2);
delay(delayTime);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
} 4.97V on 5V rail.
Multimeter: 2.476V
Com9 Serial Mon: 2.46V
The 4.97V voltage divider of two 1kΩ resistors would be 2.485V
R1: 1.002 kΩ
R2: 993Ω
Rtotal: 1.995kΩ