Knock Sensor Module KY-031 as a toggle switch with Arduino

Today, I am experimenting with knock module KY-0131 using Arduino.


The Knock Sensor Module

The Knock Sensor Module is used to detects the knock or taps.

Parts Needed

You need to have the following parts

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

For Arduino

Wiring Photo Interrupter Module

Pin Wiring KY-010 to Arduino
OUT Digital Pin – 2

Wiring Relay

Pin Wiring relay to the Arduino
S DIgital Pin – 13
+ 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;
      state = HIGH;

    time = millis();    

  digitalWrite(outPin, state);

  previous = reading;
  • Upload the code to the Arduino.
  • knock the sensor to turn on the light.