Reference   Language (extended) | Libraries | Comparison

int analogRead(pin)

Description

Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the mini), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per A/D unit.

It takes about 100 us (.0001 s) to read an analog input, so the maximum reading rate is about 10000 times a second.

Parameters

int pin

AnalogRead() accepts one integer specifying the number of the pin to read. Values between 0 and 5 are valid on most boards, and between 0 and 7 on the mini.

Note

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

Returns

An integer value in the range of 0 to 1023.

Example

 
int ledPin = 13;       // LED connected to digital pin 13
int analogPin = 3;     // potentiometer wiper (middle terminal) connected to analog pin 3
                       // outside leads to ground and +5V
int val = 0;           // variable to store the value read
int threshold = 512;   // threshold 

void setup()
{
  pinMode(ledPin, OUTPUT);   // sets the digital pin 13 as output
  Serial.begin(9600);          //  setup serial
}

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

  if (val >= threshold) {
    digitalWrite(ledPin, HIGH);   // sets the LED on
  } else {
    digitalWrite(ledPin, LOW);    // sets the LED off
  }
}

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

See also

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.