In this write-up, we will discuss an example to explain how the analog voltage is read by the analogRead() function.
How to read analog voltage on Arduino
In Arduino, there are specified analog I/O pins, for example, we consider an Arduino Uno board, which has six pins for analog input, A0 to A5. These pins are used to take the analog signals and then these signals are converted to digital signals with the help of ADC (analog to digital converter). The ADC circuit is by default embedded on an Arduino board, this circuit converts the analog signal to digital, for example, if the voltage is 0 volt, it is converted to 0 value and if the input voltage across the pin is 5 volts, it is converted to the 1023 value of digital.
Example of analogRead() in Arduino
We will try to explain the process of reading analog signals with the help of an example, we will vary a voltage with the help of a potentiometer and read its output on the serial monitor and serial plotter. For this purpose, we need the following components:
- Breadboard
- Connecting wires
- Potentiometer
We will connect one leg of the potentiometer with the 5 volts and the other end leg with the ground, the middle leg of the potentiometer is connected to A4 which is an analog input pin. The circuit diagram will be like this:
We will open the IDE and type the following Arduino code for reading the analog voltage using the above potentiometer:
Serial.begin(9600);
}
void loop() {
int in=analogRead(A4);
Serial.println(in);
delay(1000);
}
Explanation to code: In the above code, in the loop section, we declare a variable “in” of integer data type and store the value of analogRead() function which was taking input from pin A4 of Arduino. Then with the help of println() we print the analog value converted to digital through serial communication at a baud rate of 9600. We generate a delay of one second between every iteration. The serial monitor output is:
We can visualize the above result on serial plotter as well:
The hardware configuration of the circuit is:
Conclusion
We can read the analog voltage signals from the analog I/O pins of the Arduino board and this input is converted to the digital values using the ADC. In this write-up, we have demonstrated an example of reading analog voltage input and visualized the results on a serial monitor as well as a serial plotter.