Description

Reads the value from a specified analog input pin.

An Arduino UNO, for example, contains a multichannel, 10-bit analog to digital converter (ADC). This means that it will map input voltages between 0 and the operating voltage (+5 VDC) into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or 0.0049 volts (4.9 mV) per unit.

The voltage input range can be changed using analogReference(). The default analogRead() resolution on Arduino boards is set to 10 bits, for compatibility. You need to use analogReadResolution() to change it to a higher resolution.

Syntax

Use the following function to get a sample reading of an analog input:

analogRead(pin)

Parameters

The function admits the following parameter:

pin: the name of the analog input pin to read from.

Returns

The function returns the analog reading on the pin. Although it is limited to the resolution of the analog to digital converter (0-1023 for 10 bits, 0-4095 for 12 bits, etc). Data type: int.

Example Code

The code reads the analog value on analogPin and displays it.

int analogPin = A3; // potentiometer wiper (middle terminal) connected to analog pin 3
                    // outside leads to ground and VCC
int val = 0;  // variable to store the value read

void setup() {
  Serial.begin(9600);           //  setup serial
}

void loop() {
  val = analogRead(analogPin);  // read the input pin
  Serial.println(val);          // debug value
  delay(200);
}

You can convert the raw analog reading into a voltage value by using the following method:

// Constants
const float V_REF = 5.0;     // Analog reference voltage (e.g., 5V or 3.3V)
const float R_BITS = 10.0;   // ADC resolution (bits)
const float ADC_STEPS = (1 << int(R_BITS)) - 1; // Number of steps (2^R_BITS - 1)

const int potentiometerPin = A3; // Potentiometer wiper connected to analog pin A3

void setup() {
  Serial.begin(9600); // Initialize serial communication
  Serial.println(ADC_STEPS);
}

void loop() {
  int rawValue = analogRead(potentiometerPin); // Read the analog input
  float voltage = (rawValue / ADC_STEPS) * V_REF; // Convert to voltage

  Serial.print("Voltage: ");
  Serial.print(voltage, 3); // Print voltage with 3 decimal places
  Serial.println(" V");
  
  delay(200); // Small delay to avoid flooding the serial monitor
}

Notes and Warnings

If the analog input pin is not connected to anything, the value returned by analogRead() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to the board, etc.).

See also