For this assignment, I was inspired by the lighting system in my car. The headlights can be turned on automatically, but my car can detect darkness/brightness to turn them off or on automatically. This means, for example, that if I enter a dark tunnel during the day, the headlights will automatically turn on.
So, I thought I’d create some sort of system where in darkness, a LED turns on, while in brightness, the LED turns off. Simultaneously, there is another LED which can be toggled on and off with a button. That would be in the case that the analog LED is not displaying the result that the user wants, and therefore the user can turn it on or off manually, replicating the headlight system in my car.
The components I used for this assignment were:
• 1 photoresistor
• 1 x button
• 2 x yellow LEDs
• 2 x 330 ohm resistors
• 2 x 10K ohm resistors
• Wires
• Arduino and Breadboard
My final setup looked like this:
And this is my code!
int sensorLEDPin = 11; // Photosensor LED int buttonLEDPin = 13; // Button LED int buttonPin = 2; // Pin connected to button bool ledState = false; // LED state; boolean variable bool lastButtonState = HIGH; // Last state of the button; boolean variable void setup() { Serial.begin(9600); pinMode(sensorLEDPin, OUTPUT); // Setting output pins pinMode(buttonLEDPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); // Setting the initial state of the button as HIGH } void loop() { int sensorValue = analogRead(A3); sensorValue = constrain(sensorValue, 390, 640); // Constraining the sensor value int brightness = map(sensorValue, 390, 640, 255, 0); // Mapping the sensor value to brightness so that when it is dark, LED is brighter analogWrite(sensorLEDPin, brightness); // Uses the sensor to determine brightness int buttonState = digitalRead(buttonPin); // Reading current state of the button (HIGh or LOW) if (buttonState == LOW && lastButtonState == HIGH) { ledState = !ledState; // Toggling the state of Button LED delay(50); } lastButtonState = buttonState; // Updating the last state to be the current state digitalWrite(buttonLEDPin, ledState ? HIGH : LOW); // Control LED based on button Serial.println(sensorValue); delay(100); }
Finally, here is a schematic of my circuit: