Lets take a look at creating some automations within ESPHome on the device itself without needing to have Home Assistant present.
In our last video/article Getting Started with ESPHome – Average Automation we created a basic sensor in ESPHome that we will continue top use in this one to add some automation functionality to it.
A quick note on this, If you setup automations within a ESPHome device it will always be active and trigger every time that condition is met, meaning if you also setup automations in Home Assistant this can cause a conflict and a lot of Troubleshooting, I would recommend to make sure the automations work together instead of against each other.
Here is the Code changes Made for automating a relay based on temperature.
Relay based on Temperature
switch:
- platform: gpio
pin: GPIO05
inverted: true
name: "Relay"
id: relay
sensor:
- platform: dht
pin: GPIO04
temperature:
name: "DHT Temp"
on_value_range:
- above: 23.0
then:
- switch.turn_on: relay
- below: 22.0
then:
- switch.turn_off: relay
humidity:
name: "DHT Humidity"
update_interval: 10s
I have Highlighted the changes we made from our previous code in red.
In order to use of call a device in ESPHome we need to supply it with a ID in this case we game the ID of “relay” to our relay.
Then under the Temperature we added a few lines this is really easy to decipher for anyone working with these devices.
With the changes to the code the function will Turn on the relay when the temperature is above 23 degrees and once the temperature goes below 22 degrease the relay will turn off again.
Adding a switch/Button
We can also add a switch/button to this automation in the code below I have also added a Temporary push button to the esp and setup a automation to trigger according to the button press events.
switch:
- platform: gpio
pin: GPIO05
inverted: true
name: "Relay"
id: relay
binary_sensor:
- platform: gpio
pin: GPIO02
name: "Door"
device_class: door
on_click:
min_length: 60ms
max_length: 950ms
then:
- switch.turn_on: relay
sensor:
- platform: dht
pin: GPIO04
temperature:
name: "DHT Temp"
on_value_range:
- above: 23.0
then:
- switch.turn_on: relay
- below: 22.0
then:
- switch.turn_off: relay
humidity:
name: "DHT Humidity"
update_interval: 10s
As you can see this is also fairly simple to read the changes, you may notice the min_length: and max_length: in this example, this is used to avoid false positives that you may run into when using longer wire or have weird interference to not trigger a unwanted trigger.
min_length: 60ms This means that the button needs to be pressed for at least 60ms
max_length: 950ms this means that the button should not be pressed for longer than 950ms or almost a second, if it is pressed longer than the specified 950ms it will not trigger the automation
This works almost like a Filter to filter out false positives that is sometimes present.