int analogRead(pin)

Description

Reads the value from a specified analog pin, the Arduino board makes a 10-bit analog to digital conversion. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1024.

Parameters

You need to specify the number of the pin you want to read. It has to be one of the analog pins of the board, thus it should be a number between 0 and 5. It could also be a variable representing one value in that range.

Note

Analog pins unlike digital ones, do not need to be declared as INPUT nor OUTPUT

This function returns

An integer value in the range of 0 to 1024.

Example

 
int ledPin = 13;   // LED connected to digital pin 13
int analogPin = 3;   // potentiometer connected to analog pin 3
int val = 0;   // variable to store the read value
int threshold = 512;   // threshold 

void setup()
{
  pinMode(ledPin, OUTPUT);   // sets the digital pin 13 as output
}

void loop()
{
  val = analogRead(analogPin);   // read the input pin
  if (val >= threshold) {
    digitalWrite(ledPin, HIGH);   // sets the LED on
  } else {
    digitalWrite(ledPin, LOW);   // sets the LED on
  }
}

Sets pin 13 to HIGH or LOW depending if the input at analog pin is higher than a certain threshold.

See also

Reference Home