Light Activated Nightlight

Step 1 - Build the Project

Use a light sensor to trigger an LED on or off based on the light in your environment. 

Step 2 - Upload the Code

/* * Turn on an LED when light level falls below a certain level. You * might need to change the levels to reflect your environment. */ void setup() { pinMode(A2,INPUT_PULLUP); //Light sensor pinMode(6,OUTPUT); //LED } void loop() { if (analogRead(A2) > 300){ //If dark enough, turn LED on digitalWrite(6,HIGH); } else { //If light enough, turn off digitalWrite(6,LOW); } } //Notice how the light flickers? That's when your light reading is very //near the threshold. The Dual_Threshold_Nightlight project solves this. // (c) 2017 Let's Start Coding. License:

Step 3 - Read the Walkthrough

In the setup() section of the code, set the light sensor as an INPUT_PULLUP with pinMode(). This way, a dark room will send a value near 1000 to the Maker Board and a light room will send a value near 0. 

Next, set the LED pin as an OUTPUT in the code so it receiving instructions from the code, not trying to send data in to the code. 

The loop() contains an if-else statement. Your code will make a decision by asking the question "Is the analogRead(A2) value higher than 300?". If it is, the code between the curly braces { } will run, turning pin 6 HIGH.

The else statement is only checked if the 'if' statement is false. You can also think of it as an 'otherwise' statement. If the analogRead(A2) is not above 300, pin 6 is written LOW, turning off the LED. There you have it!