ESP32 KY-021 Mini Magnetic Reed Switch Module
The KY-021 is a mini magnetic reed switch module that detects the presence of a magnetic field. It provides a digital signal output, making it suitable for applications like security systems, position sensors, and magnetic field detection projects.
🔗 Quick Links
🛒 KY-021 Price
ℹ️ About KY-021 Mini Magnetic Reed Switch Module
The KY-021 Mini Magnetic Reed Switch Module is designed to detect the presence of a magnetic field. It contains a reed switch that closes its contacts when exposed to a magnetic field, allowing current to flow through. This module operates at voltages between 3.3V and 5V, making it compatible with various microcontrollers like Arduino and ESP32. It's commonly used in applications such as door and window sensors, position detection, and other projects requiring magnetic field detection.⚙️ KY-021 Sensor Technical Specifications
Below you can see the KY-021 Mini Magnetic Reed Switch 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 - 5V
- Output Type: Digital
- Dimensions: 19 x 18.5 x 9 mm
🔌 KY-021 Sensor Pinout
Below you can see the pinout for the KY-021 Mini Magnetic Reed Switch 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 (-):
Connects to ground (GND).Pin (middle):
Connects to VCC (3.3V to 5V).Pin (S):
Outputs the digital signal; connect to a digital input on your microcontroller.
🧵 KY-021 Wiring with ESP32
Below you can see the wiring for the KY-021 Mini Magnetic Reed Switch 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.
KY-021 Pin (-):
Connect to ESP32GND
.KY-021 Pin (middle):
Connect to ESP323.3V
.KY-021 Pin (S):
Connect to a digital GPIO pin on ESP32 (e.g.,GPIO4
).
🛠️ KY-021 Mini Magnetic Reed Switch 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 output any signal when a magnet is nearby.
Solutions:
- Verify that all connections are secure and correctly placed.
- Ensure the module is receiving the appropriate voltage (3.3V to 5V).
- Check if the microcontroller's digital input pin is correctly configured.
- Test the reed switch with a multimeter to confirm it closes when exposed to a magnetic field.
⚠️ False Triggering
Issue: The sensor outputs a signal without a magnet nearby.
Solutions:
- Ensure stable mounting to prevent unintended movements.
- Check for loose connections or interference from nearby electronic components.
- Implement software debouncing to filter out spurious signals.
- Verify that there are no stray magnetic fields in the environment causing false triggers.
💻 Code Examples
Below you can find code examples of KY-021 Mini Magnetic Reed Switch Module with ESP32 in several frameworks:
If you encounter issues while using the KY-021 Mini Magnetic Reed Switch Module, check the Common Issues Troubleshooting Guide.

ESP32 KY-021 Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the KY-021 Mini Magnetic Reed Switch Module:
int reed_magnet = 10; // Declaration of the sensor input pin
int value; // Temporary variable
void setup() {
pinMode(reed_magnet, INPUT); // Initialization sensor pin
Serial.begin(9600); // Initialization of the serial monitor
Serial.println("KY-021 Magnetic field detection");
}
void loop() {
// The current signal at the sensor is read out
value = digitalRead(reed_magnet);
// If a signal could be detected, this is displayed on the serial monitor.
if (value == LOW) {
Serial.println("Magnetic field detected");
delay(100); // 100 ms break
}
}
This Arduino code sets up the KY-021 reed switch on digital pin 10. It reads the digital value corresponding to the presence of a magnetic field and prints a message to the serial monitor when a magnetic field 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.

ESP32 KY-021 ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the KY-021 Mini Magnetic Reed Switch 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 REED_SWITCH_PIN GPIO_NUM_4
void app_main(void) {
gpio_config_t io_conf = {
.pin_bit_mask = (1ULL << REED_SWITCH_PIN),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE
};
gpio_config(&io_conf);
printf("KY-021 Magnetic Field Detection Test\n");
while (1) {
int level = gpio_get_level(REED_SWITCH_PIN);
if (level == 0) {
printf("Magnetic field detected\n");
vTaskDelay(pdMS_TO_TICKS(100)); // 100 ms delay
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
This ESP-IDF code configures GPIO4 as an input with an internal pull-up resistor for the KY-021 reed switch. It continuously checks the pin state and prints a message when a magnetic field is detected.
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.

ESP32 KY-021 ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the KY-021 Mini Magnetic Reed Switch Module
binary_sensor:
- platform: gpio
pin:
number: GPIO4
mode: INPUT_PULLUP
name: "KY-021 Magnetic Reed Switch"
filters:
- delayed_on: 50ms
- delayed_off: 50ms
on_press:
- then:
- lambda: |-
ESP_LOGD("sensor", "Magnetic field detected!");
This ESPHome configuration sets up the KY-021 reed switch as a binary sensor on GPIO4. The internal pull-up resistor is enabled, and debounce filters are applied to prevent false triggers. When the sensor detects a magnetic field, a log message is generated.
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.

ESP32 KY-021 PlatformIO Code Example
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-021 PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the KY-021 Mini Magnetic Reed Switch Module:
#include <Arduino.h>
#define REED_SWITCH_PIN 4
void setup() {
pinMode(REED_SWITCH_PIN, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("KY-021 Magnetic Field Detection Test");
}
void loop() {
if (digitalRead(REED_SWITCH_PIN) == LOW) {
Serial.println("Magnetic field detected");
delay(100);
}
delay(100);
}
This PlatformIO code configures GPIO4 as an input with a pull-up resistor for the KY-021 reed switch. It detects magnetic fields and prints a message when a field is detected.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.

ESP32 KY-021 MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the KY-021 Mini Magnetic Reed Switch Module with your ESP32.
import machine
import time
REED_SWITCH_PIN = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
while True:
if REED_SWITCH_PIN.value() == 0:
print("Magnetic field detected")
time.sleep(0.1)
time.sleep(0.1)
This MicroPython script configures GPIO4 as an input with an internal pull-up resistor for the KY-021 reed switch. It continuously checks the sensor state and prints a message when a magnetic field is detected.
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-021 Mini Magnetic Reed Switch Module, its pinout, connection with ESP32 and KY-021 Mini Magnetic Reed Switch Module code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.