I started off by using the photoresistor. The photoresistor is a light sensitive resistive sensor which means that as a lot of light hits the top of the sensor, it has low resistance.
I followed the diagram below create a circuit that lights up an LED when light hits the photoresistor.
I wrote up the code below. It basically reads the input from the photo-resistor at pin A0 and maps that onto the scale for LED pwm (pulse-width-modulation). That number is stored in a variable called ledBrightness and is reflected when the LED lights up by analogWrite statement.
This worked! Yay! However, the mapping scale was not making the LED show enough contrast between the dimmest and brightest frequency. Therefore I changed the mapping to the code below:
The next exercise I tried was combining a switch button input with the photo-resistor and LED output. Here was the diagram I used to integrate a button into the mix.
Here is the completed circuit with the switch. When the switch is turned on, the photo-resistor takes in a light reading and it displays on the LED (with it being lit up if there is a lot of light). When the switch is turned off, the LED light is off too.
I had a tough time understanding what was going wrong with my circuit because it was not working at first. I was connected the terminal of the switch to ground, but not to the power. Also in my code, I was only reading the switch input once. I had to move that line into the loop.
To me, having the LED light up when the photo-resistor detects less light makes more sense to me. This way the LED is offering more light in a darker environment. To do this, I had to change the mapping for the ledBrightness, which was one line of code.