Arduino Nano - Light Sensor LED
This tutorial instructs you how to use Arduino Nano and light sensor to trigger LED. In detail:
- Arduino Nano turns on the LED if the analog value of the light sensor is lower than a certain threshold (when dark)
- Arduino Nano turns off the LED if the analog value of the light sensor is greater than a certain threshold (when light)
The light sensor is also known as photoresistor, light-dependent resistor, photocell, LDR. Arduino Nano measures the light level of ambience via a light sensor, if it is dark, Arduino Nano turns on LED and vice versa.
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.
Additionally, some of these links are for products from our own brand, DIYables.
Overview of LED and Light Sensor
If you are unfamiliar with LED and light sensor (pinout, functionality, programming ...), please refer to the following tutorials:
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
Arduino Nano Code
/*
* This Arduino Nano code was developed by newbiely.com
*
* This Arduino Nano code is made available for public use without any restriction
*
* For comprehensive instructions and wiring diagrams, please visit:
* https://newbiely.com/tutorials/arduino-nano/arduino-nano-light-sensor-led
*/
const int LIGHT_SENSOR_PIN = A0; // The Arduino Nano pin connected to light sensor's pin
const int LED_PIN = 2; // The Arduino Nano pin connected to LED's pin
const int ANALOG_THRESHOLD = 500;
int analog_value;
void setup() {
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
}
void loop() {
analog_value = analogRead(LIGHT_SENSOR_PIN); // read the input on analog pin
if(analog_value < ANALOG_THRESHOLD)
digitalWrite(LED_PIN, HIGH); // turn on LED
else
digitalWrite(LED_PIN, LOW); // turn off LED
}
Detailed Instructions
- Connect your Arduino Nano to your computer using a USB cable.
- Launch the Arduino IDE, select the appropriate board and port.
- Copy the code above and open it in the Arduino IDE.
- Click the Upload button in the Arduino IDE to compile and upload the code to the Arduino Nano.
- Emit light source towards the sensor
- Check out the LED's state
Code Explanation
Check out the line-by-line explanation contained in the comments of the source code!