Basic analogRead in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Converting analog values to digital is a common requirement from microcontrollers in general, and Arduino is no different. Arduino IDE has a built-in analogRead function to facilitate the conversion of analog values to digital.

From the programming perspective, the only thing you require to know is the pins of your microcontroller that support ADC. On the Arduino UNO board, the pins A0 to A5 support ADC.

Now, let us assume that you've connected your A0 pin to an analog wire (maybe the junction between an LDR and a resistor, or the central leg of a potentiometer).

The basic Arduino code to print the analog readings is −

Example

int sensorPin = A0;      // select the input pin for the potentiometer
void setup() {
}
void loop() {
   // read the value from the sensor:
   sensorValue = analogRead(sensorPin);
   print(sensorValue);
   delay(1000);  
}

As you can see, there are no initializations required in the setup. The analogRead function will read the input voltage coming in on A0 pin, compare it with 5V, and scale it to 1024 (default resolution is 10-bit). Thus, if there is 5V coming on A0 pin, the value printed will be 1024. If there is 2.5V coming on A0 pin, the value printed will be 2.5/5*1024 = 512.

raja
Published on 23-Mar-2021 11:46:05
Advertisements