PROJECT: Sleep Friendly Nightlight
Step 1 - Build the Project
Create a smart night light that comes on when the room gets dark. After you turn it off with a clap, it won't turn on again until the next night.
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
At the top of your code, create an 'int' type variable called state. State will toggle between 0 and 1 when multiple conditions are true. It starts out as a 0.
In the setup() section of the code, set the pinMode of each of your sensors and the LEDs.
In the loop of the code, first create two variables for the readings from your sensors. This makes it easier for you to use these readings later. It also ensures you're only using one reading per loop instead of taking a new reading in each 'if' statement.
Using a series of 'if' statements, you can determine which state the night light is in. There are 3 possible states:
1) The night light is turned off in a bright room and is waiting for darkness.
2) The night light is in a dark room and it's been waiting for darkness to turn on, so it turns on.
3) The night light is on in a dark room and there was a clap in the room, so the night light turns off.
The first if statement checks the light level. If it is bright in the room, the LED turns off and the state variable is set to 0.
The if following checks for two conditions that both must be true. It asks the questions "Is the lightValue greater than 400?" and "Is the state variable equal to 0?". If the answer to both of those is "yes", the LED is turned on and the state variable is set to 1.
The next else-if statement is only checked if the statement above it is false. This statement also requires two things to be true for the code to run. There must be a soundValue greater than 600 and the state of the night light must equal 1. This ensures that noises that happen while the night light is off don't try to trigger code. If both the statements are true, the LED is turned off.
Note here that you cannot reset state to 0 when you clap. If you did, the loop would start back over and the light would come back on in a dark room!
The final if statement checks the light value. If the light sensor senses bright light, the state is reset to 0, to the night light is waiting for darkness to come on again. By separating the code that resets the system from the code that turns off the light, you avoid an endless loop of the light turning on and off again.