Arduino Mega - Light Sensor
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
Everything below is what the build uses. The links go to the parts we make and test.
- Arduino MEGA
- DIYables MEGA Development Board
- USB 2.0 cable type A/B (for USB-A PC)
- USB 2.0 cable type C/B (for USB-C PC)
- Light Sensor
- 10 kΩ Resistor
- Breadboard
- Jumper Wires
- Screw Terminal Block Shield for Arduino Uno/Mega
- Sensors/Servo Expansion Shield for Arduino Mega
- Breadboard Shield for Arduino Mega
- Enclosure for Arduino Mega
- DIYables Sensor Kit (18 sensors/displays)
Wiring
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.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/arduino-mega/arduino-mega-light-sensor