Arduino Mega - Light Sensor

by DIYables in Circuits > Arduino

16 Views, 0 Favorites, 0 Comments

Arduino Mega - Light Sensor

arduino-mega-light-sensor-cover.jpg

This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://newbiely.com/tutorials/arduino-mega/arduino-mega-light-sensor

This build shows how to read ambient light with an Arduino Mega and a photoresistor (LDR). The sensor's resistance drops as light increases and rises in the dark, and the Mega reads that change through one of its analog pins to give a rough brightness reading on the Serial Monitor.

Supplies

Wiring

arduino-mega-light-sensor-wiring-diagram.jpg

The LDR is a plain photoresistor with two interchangeable pins, so there is no polarity to worry about. Because it only changes resistance, it needs the 10 kΩ resistor to form a voltage divider so the Arduino can read a voltage instead of a resistance. Wire the LDR and resistor in series, and connect the midpoint between them to an analog input pin on the Arduino Mega, A0 in this example.

How It Works

The Mega's A0-A5 pins are analog inputs that convert a voltage between 0 V and VCC into a number from 0 to 1023, called the ADC value. As light hits the LDR, its resistance changes, which changes the voltage at the midpoint of the divider. analogRead() picks up that voltage as a number: low light gives high resistance and a different reading than bright light, so the ADC value tracks how bright or dark it is.

Code

The sketch starts serial communication at 9600 bps, then in loop() calls analogRead(A0) to get a value between 0 and 1023. It prints the raw reading, then checks it against a few thresholds to print a word alongside it: Dark, Dim, Light, Bright, or Very bright. A 500 ms delay sets the pace of the readings printed to the Serial Monitor.

arduino-mega-light-sensor.ino - the sketch from the tutorial, unchanged.

/*
* This Arduino Mega code was developed by newbiely.com
*
* This Arduino Mega code is made available for public use without any restriction
*
* For comprehensive instructions and wiring diagrams, please visit:
* https://newbiely.com/tutorials/arduino-mega/arduino-mega-light-sensor
*/

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
// reads the input on analog pin A0 (value between 0 and 1023)
int value = analogRead(A0);

Serial.print("Analog reading: ");
Serial.print(value); // the raw analog reading

// We'll have a few threshholds, qualitatively determined
if (value < 10) {
Serial.println(" - Dark");
} else if (value < 200) {
Serial.println(" - Dim");
} else if (value < 500) {
Serial.println(" - Light");
} else if (value < 800) {
Serial.println(" - Bright");
} else {
Serial.println(" - Very bright");
}

delay(500);
}

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/arduino-mega/arduino-mega-light-sensor