Analog Input

An analog input can measure a voltage difference. Many phenomena can be measured with simple sensors that output analog voltage value, for example, sound, light intensity, and or preasure. Therefore the Arduino offers the analog inputs (A0-A5) to read such values. To be able to detect a voltage difference (analog signal), the Arduino has a 6 channel, 10-bit analog to digital converter (AD converter). A resolution of 10-bit means that the Arduino detects a voltage difference from 0V to 5V with a resolution of 10-bit. It, therefore, delivers 1024 different values for this range (this corresponds to an accuracy of 4.9 mV per step).
For our purposes, a 10-bit resolution is sufficient. However, there are much more accurate analog to digital converters, with say 16-bit (65535 values) or even 32-bit (approx. 4.3 million values).

Function

To read a signal at an analog pin we use the function analogRead(Pin_Number). This function directly returns us a number between 0 and 1024. We don't need to call pinMode(PIN, MODE) in setup() for this function as we do for digital pins.

Example with a Photo Resistor

One type of simple sensor is a photoresistor. It changes its electrical conductivity (resistance) depending on the incidence of brightness and can therefore also be called a brightness sensor. Many sensors also act as a variable resistor, and unfortunately our arduino isn't designed to measure resistance; we need to convert this resistance to a variation in voltage. To do this, we need a so-called voltage divider circuit.

Voltage Divider

With the help of a voltage divider, we can measure differences in the voltage ratio of two resistors between 0V and Vcc (in our case 5V). Typically one of the resistors is a sensor (variable resistor) and one is a fixed resistor. The circuit looks like this:¨

Exercise

Build a circuit and code it to turn on an LED when it gets dark using a Photoresistor.

Optional: code it so the LED fades smoothly between dark and light states.

// Define pins const int sensorPin = A0; // Light sensor on analog pin A0 const int ledPin = 12; // LED on digital pin 12 void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(ledPin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: int sensorValue = analogRead(sensorPin); if (sensorValue <= 200) { // this value should be changed depending on your light conditions, resistors etc. digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } Serial.println(sensorValue); delay(50); }