ESP32 AM312 motion sensor automation
DIY 5 minutes : Connect esp32 to the motion sensor am312 and create an automation.
In the last article, we’ve seen how to turn on/off the smart light depending on the presence of your smartwatch. In this article, we will see how to turn on/off the light using the PIR motion sensor AM312.
Requirements
Before starting the tutorial, you should have these materials.
Aliexpress:
ESP32-DevKitC board : Buy here from aliexpress
AM312 Motion sensor : Buy here from aliexpress
Tuya wifi bulb : Buy here from aliexpress
Wiring the components
AM312 has 3 pins: 5v, GND and DATA. The DATA pin should be connected to a non-reserved
pin on esp32. I’ve chosen GPIO13.
Wire the AM312 pir sensor to esp32 as following:
AM312 | ESP32 |
---|---|
GND | GND |
5V | 5V |
Data | GPIO13 |
ESPhome configuration
If you are not familiar with esphome [check this article](/how-to-monitor-your-home-temperature-with-esp32-and-xiaomi-mijia-using-esphome/.
Run ESPhome on your computer, and prepare the esp32 configuration:
- Create a config file
motionsensor.yaml
under config directory. - Add the following configuration to the file.
substitutions:
# Modify variables based on your settings
hostname: "pirsensor"
esphome:
name: $hostname
platform: ESP32
board: esp32dev
wifi:
ssid: wifi_ssid
password: wifi_password
fast_connect: True
# Enable logging
logger:
# Enable Home Assistant API
api:
reboot_timeout: 0s
web_server:
port: 80
ota:
# Example configuration entry
binary_sensor:
- platform: gpio
pin: 13
name: "PIR Sensor"
device_class: motion
Now you can flush your esp32
with the configuration above.
Configuring smartbulb
If your smart bulb is not configured yet, you can refer to this video to see how to setup it.
Home assistant automation
Once your esp32 is configured, connected to the wifi and to home assistant, let’s create the automation.
Indeed, 2 automations are required :
- When the PIR is ON, turn on the light
- When the PIR is OFF, turn OFF the light after 1 minute
In the ${HOME_ASSISTANT_DIR}/config
, add the following configuration to the automations.yaml
:
- alias: Room Motion On
trigger:
- platform: state
entity_id: binary_sensor.pir_sensor
to: "on"
condition:
- service: light.turn_on
# light.myroom is the home assistant ID of my smart bulb in home assistant
entity_id: light.myroom
- alias: Room Motion Off
trigger:
- platform: state
entity_id: binary_sensor.pir_sensor
to: "off"
for:
minutes: 1
action:
- service: light.turn_off
entity_id: light.myroom
If you like this tutorial, please give me support by subscribing to my Youtube channel my youtube channel
I hope this article was useful, please write a comment if you succeed and share it with your friends!