LESSON 4 :
Analog Input
As you learned in the previous lessons, Arduino is able to detect whether there is a voltage applied to one of its pins and report it through the digitalRead()function.
but light sensor such as ( LDR ) is able to tell us not just whether there is light, but also how much light there is. This is the difference between an on/off sensor (which tells us whether something is there) and an analogue sensor, whose value continuously changes.
In order to read this type of sensor, we can use the six pins marked “Analog In” in the lower-right part of the Arduino board.
In order to read this type of sensor, we can use the six pins marked “Analog In” in the lower-right part of the Arduino board.
By using the analogRead() function, we can read the voltage applied to one of the pins. This function returns a number between 0 and 1023, which represents voltages between 0 and 5 volts. For example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0)returns 512.
Now we will use LDR in a simple program.we will set the brightness of LED to a value specified by an analog input comming from LDR ( i.e. if it's dark the LED will be highly brighted and if it's well lighted the LED will have faint brightness).
The LDR is connected to the arduino board as shown in the following figure :
And the LED is connected to pin 9 as in previous lessons.
here is the code :
// Example 06B: Set the brightness of LED to a brightness specified by the
// value of the analogue input
const int LED = 9; // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup()
// value of the analogue input
const int LED = 9; // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup()
{
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop()
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop()
{
val = analogRead(0); // read the value from the sensor
analogWrite(LED, val/4); // turn the LED on at
// the brightness set by the sensor
delay(10); // stop the program for some time
}
val = analogRead(0); // read the value from the sensor
analogWrite(LED, val/4); // turn the LED on at
// the brightness set by the sensor
delay(10); // stop the program for some time
}
NOTE: We specify the brightness by dividing valby 4, because analogRead()returns a number up to 1023, and analogWrite() accepts a maximum of 255.
Arduino language tutorial (Lesson 4)