Sensors | Car Headlights


In this assignment, I implemented a circuit with an LDR sensor and a switch that were both used to replicate some basic functionality of car headlights.

I built an Arduino circuit that used an analog sensor and a digital sensor to control two LEDs – ‘car headlights’. Using a switch, I made two LEDs blink periodically as long as the switch is still pressed. By default state when the switch is released, two LEDs will have the brightness controlled by an LDR sensor. So, the idea was to reduce brightness when the LDR reading is high and increase it if it is low.



If the switch is pressed, then 2 LEDs are blinking with some delay. If not, then the code uses the LDR value to set the brightness of LEDs to the appropriate value.

const int switchPin = 3; // the pin that the switch is connected to
const int ledPin1 = 6;   // the pin that the first LED is connected to
const int ledPin2 = 9;  // the pin that the second LED is connected to
const int ldrPin = A0;   // the pin that the LDR sensor is connected to

int switchState = 0;     // variable for reading the switch status
int ldrValue = 0;        // variable for storing the LDR sensor reading
int ledBrightness1 = 0;  // variable for storing the brightness of the first LED
int ledBrightness2 = 0;  

void setup() {
  pinMode(switchPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);

void loop() {
  // read the switch state
  switchState = digitalRead(switchPin);

  // blink the LEDs if the switch is pressed
  if (switchState == LOW) {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, HIGH);
  } else {
    // read the LDR sensor value
    ldrValue = analogRead(ldrPin);

    // map the LDR sensor value to the LED brightness range (0-255)
    ledBrightness1 = map(ldrValue, 0, 1023, 255, 0);
    ledBrightness2 = map(ldrValue, 0, 1023, 255, 0);

    // adjust the LED brightness
    analogWrite(ledPin1, ledBrightness1);
    analogWrite(ledPin2, ledBrightness2);

  // print the LDR sensor value to the Serial Monitor


Future changes

I feel that there is a lot of room for improvement in setting the brightness using an LDR sensor. The LEDs actually keep being bright with high LDR values, and it is a bit hard to get LDR values to the low level. Yet, the LDR sensor does make them brighter when the LDR readings become low eventually.

Leave a Reply