Hey guys, this is your hardware friend kayode. Hope you have been good? Well today we will focus on reading analog voltage with our arduino. Signals that we make use of and that surround us are usually analog that is they vary with time. A good example of an analog signal is the electricity supply we have in our homes. It is a sine wave that varies with time. Since we now know that the analog signals are very useful, it will be cool to know how to read them.
They AT-mega328 on the arduino board has a number of peripherals one of which is the analog to digital converter (ADC). The microcontroller can only read digital signals and therefore we have to convert our analog signal to a digital one. The arduino has a 6 channel 10-bit analog to digital converter. The channels are labeled A0-A5. In this tutorial, we are going to read an analog input from a potentiometer on pin A0, convert it to voltage, and print the result to the serial monitor.
First, let’s understand how the arduino measures the analog signal. Earlier, we learnt about the digitalRead() function which reads either a HIGH or a LOW. The opposite of the digitalRead() function is the analogRead() function. This function reads the voltage on any of the analog channels and returns an integer of between 0 and 1023. So if we have 0V the function will return 0 and if we have 5V the function will return 1023. We will need the following components;
- Arduino uno
- Potentiometer (10K)
- Jumpers
Circuit Diagram
Connect the components as shown below
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
CODE EXPLANATION
First, we start serial communication in the void setup() function
void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); }
Next, read the input on analog pin 0 and convert the analog reading (which goes from 0 – 1023) to a voltage (0 – 5V) then we print out the value on the serial monitor.
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); }
CODE
// the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: 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); }
And voila, we have successfully read the analog signal. Copy and paste the code into the IDE and open the serial monitor to see the result. Pls, let me know if you have any question.
Yours geekly,
Kayode.