KY-018 LDR Photo-Resister Module as a toggle switch with Arduino

LDR Photo-Resister Module

Photosensitive resistor module most sensitive to environmental light intensity is generally used to detect the ambient brightness and light intensity.

Parts Needed

You need to have the following parts

  • Arduino (Any version)
  • 1x KY-018
  • 1x One-Channel Relay module 5V
  • Jumper Wires

For Arduino

Wiring LDR Photo-Resister Module

PinWiring KY-018 to Arduino
OUTDigital Pin – 2
GNDGND
VCC5V

Wiring Relay

PinWiring relay to the Arduino
SDIgital Pin – 13
GND
+5V

Schematics For Arduino

Assemble all the parts by following the schematics below:

Connect the light lamp to the relay.

Coding Arduino

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = LOW;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = HIGH;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT_PULLUP);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();    
  }

  digitalWrite(outPin, state);

  previous = reading;
}
  • Upload the code to the Arduino.