How to make a proximity sensor for Xiaomi: from the scheme to the integration into the smart home

Xiaomi’s proximity sensors are an integral part of the modern smart home, but what to do if the finished solution does not fit the price, functionality or just want to create something unique? To assemble such a sensor yourself, even a beginner can, if you understand the principles of infrared (IR) or ultrasonic sensors and properly integrate them into the Mi Home ecosystem.

In this article, we will discuss three working ways to create a proximity sensor: from the simplest Arduino-based sensor and IR- sensor to an advanced solution with an ultrasonic module HC-SR04 and data transfer via Zigbee (for compatibility with Xiaomi MiJia), you will learn what components are required, how to avoid typical errors during soldering and configuration, and how to make a homemade device appear in the Mi Home app along with branded gadgets.

We’ll focus on practical nuances, from calibrating sensitivity to bypassing the limitations of Xiaomi’s firmware, which often block third-party devices. If you’ve ever thought about automating lights when you enter a room or getting a door traffic notification, this guide is for you.

1. Principle of operation of proximity sensors: what you need to know before assembly

Before you start a soldering iron, it is important to understand what the physical principles behind proximity sensors are: Xiaomi devices (such as the Mi Motion Sensor or the Aqara Human Body Sensor) most often use:

  • πŸ”΄ Infrared (PIR) sensors: They respond to heat from bodies (human, animal) and are suitable for detecting indoor motion, but have dead zones and false alarms from heating appliances.
  • πŸ”Š Ultrasonic sensors: measure the time a sound wave reflects off an object, more precisely PIR, but are sensitive to interference (e.g. fans) and require calibration.
  • πŸ“Ά Radar (microwave) sensors: used in premium devices (e.g., Aqara FP2) detect even minimal motion, but are difficult to repeat with their own hands.

For a homemade sensor, the best choice is the PIR- sensor HC-SR501 (cheap, easy to set up) or the ultrasonic HC-SR04 (for accurate distance measurement). Both options can be connected to an Arduino or ESP8266, and then integrated into the Mi Home via the MQTT protocol or Zigbee bridge (for example, CC2531).

⚠️ Attention: PIR- sensors HC-SR501 have a fixed viewing angle (~110°) and a range (~7 m). If you need to monitor a narrow corridor or staircase, use a Fresnel lens or combine multiple sensors.

The key is the logic of operation: Xiaomi’s proprietary sensors only send a signal to the Mi Home when a state changes (for example, β€œmovement detected” β†’ β€œno movement”). In a homemade device, this logic will have to be written in Arduino code or configured through the Home Assistant.

πŸ“Š What type of sensor do you plan to use?
Infrared (PIR)
Ultrasonic.
radar
I haven't decided yet.

2.Components for a homemade sensor: what to buy and where to save

The minimum set of components depends on the type of sensor chosen, and below is the checklist for the two most popular options, with average prices (2026) and places of purchase:

ComponentModel/characteristicsPrice (β‚½)Where to buy
PIR-sensorHC-SR501 (adjustable sensitivity)150–250AliExpress, Chip and Deep
Ultrasonic sensorHC-SR04 (range 2-400 cm)200–350AliExpress, Amperka
MicrocontrollerArduino Nano or ESP8266 (Wi-Fi)300–600AliExpress, local radio stores
Zigbee module (optional)CC2531 or Sonoff ZBBridge800–1500AliExpress, I take it!
Body and wires80Γ—60 mm box, 22 AWG power cable100–300Any hardware store

If the goal is to be as compatible as possible with the Mi Home, you will need a Zigbee bridge (such as Sonoff ZBBridge or Zigbee2MQTT firmware on ESP32), without which the sensor can only be connected via Home Assistant or IFTTT, which is less convenient.

  • πŸ’‘ Savings tip: Instead of using an Arduino Nano, use ESP-01 (40 percent cheaper) β€” it’s enough for simple tasks.
  • πŸ”§ A workaround: If you don’t want to solder, buy a ready-made PIR- sensor with relay (e.g. HLK-PM01) and connect it to the Xiaomi Smart Plug via the automatic rule in Mi Home.

⚠️ Warning: When buying HC-SR501, check for Sx (sensitivity) and Tx (latency) regulators. Cheap clones without them don't allow you to fine-tune the sensor to your room.

Buying. PIR-sensor HC-SR501 regulator|Choose an Arduino Nano or ESP8266|Add to the basket case with holes for the sensor|Check the presence of resistors 10kOM (for signal lifting)|Order a USB-Micro cable (for firmware)-->

3. Connection scheme and soldering: step-by-step instructions

Let's look at the PIR- build of the Arduino Nano sensor, the simplest and most reliable option.

  • πŸ”₯ Seeding iron (25–40 W) soldered.
  • πŸ”ͺ Pieces and strippers for wires.
  • πŸ“ Multimeter (for circuit check).
  • 🧲 Shrinking tube or tape.

The HC-SR501 connection to the Arduino Nano:

HC-SR501  β†’  Arduino Nano


VCC       β†’  5V




GND       β†’  GND




OUT β†’ D2 (or any other digital pin)

Procedure:

  1. Seal the wires to the sensor legs (VCC, GND, OUT). Use different colors for convenience (red plus, black minus, yellow signal).
  2. Connect the wires to the Arduino according to the circuitry. Make sure the contacts are not closed (check the multimeter in "vertebrate" mode).
  3. Lock the sensor in the case so that the Fresnel lens is pointed into the detection area. For street use, add a sealant.
  4. Connect the Arduino to your computer via USB and download the test sketch (see next section).

Critical rookie error: ignoring the pull-up resistor on the OUT pin. Without it, the sensor can falsely fire due to interference. Add a 10k resistor between the OUT and the VCC.

What if the sensor does not respond to movement?
1. Check power: HC-SR501 requires stable 5V (some Arduinos give less when powered by USB). 2. Adjust sensitivity (Sx) and latency (Tx) on the sensor board. 3. Make sure there are no heat sources (battery, lamp) in the detection area that "blind" the sensor. 4. Swap GND and VCC wires - sometimes Chinese sensors have a non-standard pattern.

4. Firmware and Logic Customization: Code for Arduino

To test the sensor is enough simple sketch, which will display the state in the Serial Monitor:

int pirPin = 2; // Pin to which the OUT sensor is connected


int pirState = LOW; // Current state




int val = 0; // Variable to read value





void setup() {




pinMode(pirPin, INPUT);




Serial.begin(9600);




}





void loop() {




val = digitalRead(pirPin);




if (val == HIGH) {




if (pirState == LOW) {




Serial.println ("Movement detected!")




pirState = HIGH;




}




} else {




if (pirState == HIGH) {




Serial.println ("No movement")




pirState = LOW;




}




}




}

Upload this code to the Arduino IDE and open the Serial Monitor (Ctrl+Shift+M). When you move in the sensor area, you should see messages.

  • ⏱️ Reduce latency (Tx) on the sensor board.
  • πŸ” Check if there are any fans or air conditioners in the detection area (they create air turbulence that PIR perceives as motion).
  • πŸ“‰ Reduce sensitivity (Sx) or close a portion of the Fresnel lens with opaque tape.

Integration with Mi Home requires Wi-Fi data transfer. Replace Arduino Nano with ESP8266 and use the PubSubClient library to send messages to the MQTT- broker (e.g. Mosquitto on the Raspberry Pi):

#include <ESP8266WiFi.h>


#include <PubSubClient.h>





const char* ssid = "Your WiFi"




const char* password = "password"




const char* mqtt_server = "192.168.1.100"; // IP of your MQTT- broker





WiFiClient espClient;




PubSubClient client(espClient);





void setup() {




pinMode(D2, INPUT);




WiFi.begin(ssid, password);




while (WiFi.status() != WL_CONNECTED) { delay(500); }




client.setServer(mqtt_server, 1883);




}





void loop() {




if (!client.connected()) { client.connect("Xiaomi_PIR_Sensor"); }




int motion = digitalRead(D2);




if (motion == HIGH) {




client.publish("home/pir/motion", "1");




delay(2000); // Delay to avoid flooding




}




}

πŸ’‘

If you don’t have your own MQTT- broker, use the free CloudMQTT or set up Home Assistant – it has a built-in broker and supports integration with Mi Home via the Xiaomi Miio plugin.

5.Integration with Mi Home: Bypassing Xiaomi's Restrictions

The main problem with homemade sensors is the lack of native support in the Mi Home, which can be solved in three ways:

  1. Using Home Assistant + Mi Home Integration: 🏠 Install Home Assistant on a Raspberry Pi or virtual machine. πŸ”Œ Connect the sensor via MQTT or ESPHome. πŸ”„ Set up Mi Home integration via the Xiaomi Miio plugin (you will need a token from your Xiaomi account).
  2. Through the Zigbee Bridge: πŸ“‘ Buy CC2531 or Sonoff ZBBridge and run it Zigbee2MQTT. πŸ”§ Connect the sensor as a Zigbee device (like an Aqara Motion Sensor). πŸ“± In the Mi Home, add the bridge as a new device via "Add Manually."

Using IFTTT (for simple scenarios)

  • 🌐 Configure ESP8266 to send HTTP- requests to IFTTT Webhooks.
  • πŸ”— Create an applet in IFTTT that sends a command to Mi Home when it receives a signal.

⚠️ Warning: After the Mi Home update in 2026, some Zigbee devices stopped being automatically detected. If the sensor doesn't appear in the app, try:

  • πŸ”„ Reset the bridge and reset the Mi Home cache.
  • πŸ“‹ Manually specify model_id in the configuration Zigbee2MQTT (e.g. lumi.motion for Aqara).
  • πŸ”‘ Change the region in the Mi Home settings to "China" (sometimes helps bypass restrictions).

πŸ’‘

Using the Zigbee bridge allows you to bypass the cloud limitations of Xiaomi, but requires constant operation of the local server (Raspberry Pi or always on PC).

Practical Applications: Automation Scenarios

When the sensor is connected to the Mi Home, you can set up automatic scripts. Here are some useful examples:

  • πŸ’‘ Smart lighting: Sensor at the door β†’ turns on Xiaomi Yeelight when moving. After 30 seconds without moving, the lights go out (set in Automation Mi Home).
  • 🚨 Security: Driving in the corridor at night β†’ sending push notifications to your phone + enabling Xiaomi Camera. Use Do Not Disturb mode in Mi Home to turn off alerts during the day.
  • πŸ• Pet control: Sensor at bowl β†’ notification if cat is not fit to eat for more than 12 hours. This will require Home Assistant with Telegram Bot plugin.

For complex scenarios (e.g., "if motion + temperature < 20Β°C β†’ turn on the heater"), use Home Assistant. Only the basic "IFTTT" conditions are available in the Mi Home.

Example of code for Home Assistant (automations.yaml file):

- alias: "Switch on the light in the hallway"


trigger:




platform: state




entity_id: binary_sensor.pir_motion




to: "on"




condition:




condition: time




after: "sunset"




before: "sunrise"




action:




service: light.turn_on




entity_id: light.yeelight_ceiling

If you have multiple sensors, group them together through a group: in configuration.yaml. This will allow you to create scenarios like β€œif any sensor on the ground floor is triggered β†’ turn on the siren”.

πŸ“Š Which automation scenario do you find most interesting?
Smart lighting
Security system
Animal control
Energy conservation
Other

7.Typical mistakes and how to avoid them

Even if you follow the instructions accurately, you can run into problems. Here are the TOP-5 errors and their solutions:

Problem.Reason.Decision
Sensor's operating without motion.Interference from electrical appliances or direct sunlightScreen the sensor with foil, reduce sensitivity (Sx)
Mi Home doesn't see the deviceIncorrect model_id in Zigbee2MQTTCheck the Zigbee2MQTT log and compare it to the list of supported devices.
ESP8266 loses Wi-Fi connectivityA weak signal or router overloadInstall static IP for sensor, use WiFiManager for autoconnection
False positives from animalsPIR- Sensor responds to heat, not object sizeInstall the sensor above 1.5 m or use the ultrasonic HC-SR04 with filtered size
Protracted response timeThe delay (Tx) on the sensor board is too largeReduce Tx to 1-2 seconds and optimize Arduino code (remove delay())

If the sensor is unstable, check the power. the Arduino Nano and ESP8266 are sensitive to voltage drawdowns. Use a stabilized 5V/1A power supply or plug in via externally powered USB-hub.

An important nuance: when using battery power (for example, from 18650), add Schottky diode (for example, 1N5817) to the circuit to protect against reverse current. This will extend the battery life by 2-3 times.

8. Alternative solutions: if you do not want to solder

Not everyone wants to mess around with rations and code. Fortunately, there are semi-finished products that can be adapted to Mi Home:

  • πŸ”Œ Ready-made sensors with Wi-Fi: πŸ“¦ Sonoff SNZB-03 (Zigbee, compatible with Mi Home via Zigbee2MQTT). πŸ“¦ Aqara Motion Sensor (officially supported by Xiaomi, but more expensive).
  • πŸ€– Using Mi Band: πŸ’ͺ Remove the PIR- sensor from the Mi Band fitness bracelet 4/5 (it is in the pulsemeter module). πŸ”§ Connect it to ESP8266 via ADC-pin (a signal amplifier will be required).
  • πŸ“± Software Sensors: πŸ“² Use an old Android device with the Tasker + AutoRemote app to emulate the motion sensor. πŸ”— Integrate via Home Assistant or IFTTT.