Skip to main content
ESPBoards

ESP32 KY-031 Knock Sensor Module

The KY-031 is a knock sensor module that detects physical impacts or vibrations. Upon detecting a knock, it outputs a digital signal, making it suitable for applications like interactive projects, security systems, or any setup requiring tap detection.

⬇️ Jump to Code Examples

Arduino Core Image
ESP-IDF Image
ESPHome Image
PlatformIO Image
MicroPython Image

🔗 Quick Links

KY-031 Knock Sensor Module Datasheet ButtonKY-031 Knock Sensor Module Specs ButtonKY-031 Knock Sensor Module Specs ButtonKY-031 Knock Sensor Module Specs Button

🛒 KY-031 Price

KY-031 Knock Sensor Module
Normally, the KY-031 Knock Sensor Module costs around 1$ per Psc.
The prices are subject to change. Check current price:

Amazon com

Amazon de logo

Aliexpress logo

ℹ️ About KY-031 Knock Sensor Module

The KY-031 Knock Sensor Module is designed to detect knocks or vibrations. When subjected to such physical impacts, the sensor's internal contacts momentarily connect, sending a digital signal. This module is ideal for projects that require tap or knock detection, such as interactive interfaces or security systems.

⚙️ KY-031 Sensor Technical Specifications

Below you can see the KY-031 Knock Sensor Module Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.

  • Type: module
  • Protocol: Digital
  • Operating Voltage: 3.3V to 5V
  • Output Type: Digital
  • Dimensions: 19mm x 15mm x 10mm
  • Weight: 2g

🔌 KY-031 Sensor Pinout

Below you can see the pinout for the KY-031 Knock Sensor Module. The VCC pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND pin is the ground connection and must be connected to the ground of your ESP32!

  • Pin S (Signal): Outputs a digital signal when a knock is detected.
  • Pin middle (+): Connects to the power supply (3.3V or 5V).
  • Pin - (GND): Connects to the ground of the circuit.

🧵 KY-031 Wiring with ESP32

Below you can see the wiring for the KY-031 Knock Sensor Module with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.

  • Pin S: Connect to a digital input pin on the ESP32 (e.g., GPIO16).
  • Pin middle (+): Connect to ESP32 3.3V or 5V.
  • Pin -: Connect to ESP32 GND.

🛠️ KY-031 Knock Sensor Module Troubleshooting

This guide outlines a systematic approach to troubleshoot and resolve common problems with the . Start by confirming that the hardware connections are correct, as wiring mistakes are the most frequent cause of issues. If you are sure the connections are correct, follow the below steps to debug common issues.

❌ No Response from Sensor

Issue: The sensor does not detect knocks or vibrations.

Solutions:

  • Verify all wiring connections are secure and correctly placed.
  • Ensure the sensor is receiving the appropriate voltage (3.3V or 5V).
  • Test the sensor with a known good microcontroller pin to rule out pin issues.

⚠️ False Triggering

Issue: The sensor outputs signals without any physical impact.

Solutions:

  • Check for external vibrations or noise that might be causing false triggers.
  • Implement software debouncing to filter out spurious signals.
  • Ensure the sensor is mounted securely to prevent unintended movements.

💻 Code Examples

Below you can find code examples of KY-031 Knock Sensor Module with ESP32 in several frameworks:

If you encounter issues while using the KY-031 Knock Sensor Module, check the Common Issues Troubleshooting Guide.

Arduino Core Image

ESP32 KY-031 Arduino IDE Code Example

Example in Arduino IDE

Fill in your main Arduino IDE sketch file with the following code to use the KY-031 Knock Sensor Module:

int knock = 10; // Sensor input pin
int value; // Variable to store sensor value

void setup() {
pinMode(knock, INPUT); // Initialize sensor pin as input
Serial.begin(9600); // Initialize serial communication
Serial.println("KY-031 Knock test");
}

void loop() {
value = digitalRead(knock); // Read sensor value
if (value == LOW) { // If knock detected
Serial.println("Knock recognized");
delay(200); // Delay to avoid multiple detections
}
}

This Arduino code initializes the sensor input pin and serial communication. In the loop, it continuously reads the sensor value and prints "Knock recognized" to the serial monitor when a knock is detected.

Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.

ESP-IDF Image

ESP32 KY-031 ESP-IDF Code Example
Example in Espressif IoT Framework (ESP-IDF)

If you're using ESP-IDF to work with the KY-031 Knock Sensor Module, here's how you can set it up and read data from the sensor. Fill in this code in the main ESP-IDF file:

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"

#define KNOCK_SENSOR_PIN GPIO_NUM_16

void app_main(void) {
gpio_config_t io_conf = {
.intr_type = GPIO_INTR_NEGEDGE, // Interrupt on falling edge
.mode = GPIO_MODE_INPUT,
.pin_bit_mask = (1ULL << KNOCK_SENSOR_PIN),
.pull_up_en = GPIO_PULLUP_ENABLE
};
gpio_config(&io_conf);

gpio_install_isr_service(0);
gpio_isr_handler_add(KNOCK_SENSOR_PIN, knock_isr_handler, NULL);

printf("KY-031 Knock Sensor Test\n");
while (1) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}

void IRAM_ATTR knock_isr_handler(void* arg) {
printf("Knock detected!\n");
}

This ESP-IDF code configures GPIO16 as an input with an interrupt on the falling edge. When a knock is detected, an interrupt service routine (ISR) is triggered, printing "Knock detected!" to the console.

Update the I2C pins (I2C_MASTER_SDA_IO and I2C_MASTER_SCL_IO) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.

ESPHome Image

ESP32 KY-031 ESPHome Code Example

Example in ESPHome (Home Assistant)

Fill in this configuration in your ESPHome YAML configuration file (example.yml) to integrate the KY-031 Knock Sensor Module

binary_sensor:
- platform: gpio
pin:
number: GPIO16
mode: INPUT_PULLUP
name: "KY-031 Knock Sensor"
filters:
- delayed_off: 200ms

This ESPHome configuration sets up a binary sensor for the KY-031 knock sensor connected to GPIO16. It uses a delayed_off filter to prevent multiple detections from a single knock.

Upload this code to your ESP32 using the ESPHome dashboard or the esphome run command.

PlatformIO Image

ESP32 KY-031 PlatformIO Code Example

Example in PlatformIO Framework

For PlatformIO, make sure to configure the platformio.ini file with the appropriate environment and libraries, and then proceed with the code.

Configure platformio.ini

First, your platformio.ini should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:

[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino

ESP32 KY-031 PlatformIO Example Code

Write this code in your PlatformIO project under the src/main.cpp file to use the KY-031 Knock Sensor Module:

#include <Arduino.h>

#define KNOCK_SENSOR_PIN 16

void setup() {
pinMode(KNOCK_SENSOR_PIN, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("KY-031 Knock Sensor Test");
}

void loop() {
if (digitalRead(KNOCK_SENSOR_PIN) == LOW) {
Serial.println("Knock detected!");
delay(200); // Debounce delay
}
delay(50);
}

This PlatformIO code sets up GPIO16 as an input with a pull-up resistor for the KY-031 knock sensor. When a knock is detected, a message is printed to the serial monitor, and a debounce delay of 200ms prevents false triggers.

Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload command.

MicroPython Image

ESP32 KY-031 MicroPython Code Example

Example in Micro Python Framework

Fill in this script in your MicroPython main.py file (main.py) to integrate the KY-031 Knock Sensor Module with your ESP32.

import machine
import time

KNOCK_SENSOR_PIN = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_UP)

while True:
if KNOCK_SENSOR_PIN.value() == 0:
print("Knock detected!")
time.sleep(0.2) # Debounce delay
time.sleep(0.05)

This MicroPython script configures GPIO16 as an input with a pull-up resistor for the KY-031 knock sensor. It continuously checks for knocks and prints a message when one is detected, with a debounce delay to prevent multiple detections from a single event.

Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy.

Conclusion

We went through technical specifications of KY-031 Knock Sensor Module, its pinout, connection with ESP32 and KY-031 Knock Sensor Module code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.