Read Analog Voltage Example

Analog Read Voltage

In this example the Arduino board reads a value from an analog input (in this case on PIN A0). The value is then converted into voltage and it is shown in to the serial monitor.

Hardware Required

  • Arduino Board
  • potentiometer

Circuit

Read analog voltage circuit 
The potentiometer has three pins. Connect the first pin to the Arduino 5V pin; the second to Analog Pin A0 and the third to the GND pin as shown in figure.

The Arduino board has an internal circuit called analog-to-digital converter. This circuit reads a changing voltage inside pins and it converts them to a value between 0 and 1023. 
Turning the knob of the potentiometer allows you to change the resistance that influence the output of the central pin (the one attached to the Analog Pin 0). 
By turning the knob all the way down, the resistance value is approximately zero, and the Arduino will read a total voltage of 5V.
When you set the potentiometer all the way up, the resistance is maximum and the Arduino will read a voltage of 0V.

Schematic

Read analog voltage schematic

Code

The first thing that this codes do in the setup function is to begin serial communications, at 9600 bits of data per second. 
This allows your board to communicate with your computer.

 
Serial.begin(9600);


Next, in the main loop of your code, you need to establish a variable to store the resistance value coming in from your potentiometer. 
The main loop read the sensor value with the analogRead function to the pin A0. After the value is stored in a variable (called "sensorValue").

 
int sensorValue = analogRead(A0);
 
 

To print the sensor value in voltage, you need to convert this value using some math formulas. 
To scale the numbers between 0.0 and 5.0, divide 5.0 by 1023.0 and multiply that by sensorValue.

 
float voltage= sensorValue * (5.0 / 1023.0);


Finally, the "Serial.println" function will allow you to display the voltage value on the Serial Monitor.

Serial.println(voltage)
 

Note: 
To open the serial monitor, go to "Tools -> Serial Monitor" or use the keyboard shortcut "CTRL-SHIFT-M" 
From the Serial Monitor you should see in real time the values representing the voltages read from PIN A0. 
If you turn the potentiometer, you can see the value changing, in real time.

 
// setup() is the first function executed when you plug you board
// or when you reset it. This funcion runs once
void setup() {
// initialize serial communication at 9600 bits per second
Serial.begin(9600);
}
 
// After the setup() function, the loop runs over and over
// until you stop the board
void loop() {
// read the input on analog PIN 0
int sensorValue = analogRead(A0);
 
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
float voltage = sensorValue * (5.0 / 1023.0);
 
// print out the value you read:
Serial.println(voltage);
}