This assignment for week 9 focuses on the two forms of input/output information. I’ve never used light sensors like the photoresistor so I wanted to experiment around with it to figure out some idea on how to use it to control LED(s). I was mostly trying out the photoresistor’s sensitivity and it turned out it’s very sensitive to light and changes in light. Because of this, I decided to combine the assignment prompts: I used a button to switch the first LED on and off, the light from which will in turn control the second LED.
Here is a diagram of my circuit, with the red and green LEDs being controlled using digital and analog signals respectively:
And following is a demo of the circuit at work. Please excuse the night mode of the video. Since I was using one LED to control another, I needed to omit all light from elsewhere.
The sensitivity of the photoresistor is quite clear. When I adjust the light, the state of the green LED changes almost immediately. When I use the button to switch the red LED on and off, the green LED follows quite closely with only a very short delay. As seen in the demo, I also try to manually block the red light from reaching the photoresistor, in which case the green LED also switches off quickly.
I’m trying to think if there is some way to scale up this circuit for some real-life applications. Perhaps the two LEDs can be positioned in two separated spaces, with one button to switch on/off one LED while the second one can be controlled by some kind of separator (door, etc.) that can block or un-block the light coming from the first LED.
Problems
I haven’t had a good history with circuits ever since high school physics. I tried to reassemble the different components like the photoresistor and the button first to test my understanding, but I forgot many details so at first I got a lot of weird readings. For instance, I forgot the 10k Ω resistor for the button so the digital reading from the button was just jumping randomly between 0 and 1. Thankfully I haven’t broken anything so far. I really hope it stays that way.
Code
const int redLedPin = 2; const int buttonPin = 3; const int greenLedPin = 4; const int photoPin = A0; bool onOff = false; bool previousButtonState = false; void setup() { pinMode(redLedPin, OUTPUT); pinMode(greenLedPin, OUTPUT); Serial.begin(9600); } void loop() { bool buttonState = digitalRead(buttonPin); if (buttonState == HIGH && previousButtonState == LOW) { onOff = !onOff; } digitalWrite(redLedPin, onOff); int photoValue = analogRead(photoPin); float mappedValue = map(photoValue, 0, 320, 0, 255); //Serial.print(photoValue); //Serial.print(" "); //Serial.println(mappedValue); analogWrite(greenLedPin, mappedValue); previousButtonState = buttonState; }