Using ESPHome to Connect to Home Assistant
Requirements: Home Assistant on a Raspberry Pi or other device
(instructions to install Home Assistant on a Raspberry Pi: https://www.home-assistant.io/installation/raspberrypi/)
We will use ESPHome to connect to The Button. ESPHome is a Home Assistant addon that lets us use a YAML file to connect a device to Home Assistant.
1. Set up ESPHome on your Home Assistant
Click the button on this page: https://esphome.io/guides/getting_started_hassio
Then click the install button on your Home Assistant screen
After it has installed, toggle on "Show in sidebar"
Click on ESPHome Builder in the sidebar and press Start Addon
2. Connect your Button to ESPHome
Go to https://web.esphome.io/?pico and click on "First Time Setup"
Follow the instructions to load the ESPHome file onto your Pico
Do not click Continue - return to your Home Assistant screen - ESPHome Builder
Click Add Device - Open ESPHome Web
Click Connect
Return to ESPHome Builder in your Home Assistant, you should see "Discovered 1 device"
Reload if it isn't there yet
Click Show and then Take Control, then Take Control again
Skip installing configuration on the device, click Close
Click Edit on the entry for your device
Enter the following YAML config - click save then exit
esphome:
name: esphome-web-9c0378
friendly_name: Button 1
min_version: 2024.11.0
name_add_mac_suffix: false
rp2040:
board: rpipicow
# Enable logging
logger:
# Enable Home Assistant APIß
api:
# Allow Over-The-Air updates
ota:
- platform: esphome
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
binary_sensor:
- platform: gpio
pin:
# GPIO pin connected to the button
number: 0
# Use the internal pull-down resistor
mode: INPUT_PULLDOWN
name: "Push Button"
id: push_button
Click the three dots and validate to ensure there are no issues with the config
Click Install
Select Manual Download
When the file is ready, click Download project
Select UF2 factory format
Bootsel - upload the file
Unplug the device from your computer and plug it into a power outlet so that we can ensure it's connecting via wifi
Home Assistant - Settings - Devices and Services
You should see the device under "Discovered" - click Add - Submit - (optional: add to area) - Finish
Find the device in your Home Assistant overview (click on the side panel)
Check that the binary sensor toggles from off to on when the button is pressed
Using umqtt to Connect to Home Assistant
Requirements: Home Assistant on a Raspberry Pi or other device
(instructions to install Home Assistant on a Raspberry Pi: https://www.home-assistant.io/installation/raspberrypi/)
1. Install MQTT on your Home Assistant if you don't have it: https://www.home-assistant.io/integrations/mqtt/
Manually enter the MQTT Broker connection details
Click on your name in the bottom left of Home Assistant Toggle on advanced mode Then, Settings - People - Users 2. Install MicroPython by following instructions here: https://www.raspberrypi.com/documentation/microcontrollers/micropython.html
(The Button uses a Pico W board, not a Pico 2 or Pico 2 W)
3. In the Thonny code editor, in the bottom right, select "MicroPython (Raspberry Pi Pico)"
4. Use Thonny to enter the following MicroPython code
WIFI_SSID and WIFI_PASSWORD are your wifi network's name and password
If you don't already have your Home Assistant's IP Address, you can add the following integration: https://www.home-assistant.io/integrations/local_ip/
import network
import time
import json
import mip
from machine import Pin, ADC
# WiFi credentials
WIFI_SSID = "Your_SSID"
WIFI_PASSWORD = "Your_Password"
# MQTT settings
MQTT_BROKER = "10.0.1.9" # Your Home Assistant IP
MQTT_PORT = 1883
MQTT_CLIENT_ID = "pico_sensor"
MQTT_USER = "mqtt-user" # If authentication is enabled
MQTT_PASSWORD = "Your_Password"
# Connect to WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print(f"Connected to WiFi: {wlan.ifconfig()}")
# MQTT connection
def connect_mqtt():
mip.install('umqtt.simple')
from umqtt.simple import MQTTClient
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD)
client.connect()
print("Connected to MQTT broker")
return client
from machine import Pin
import time
# Add these topic definitions at the top with your other constants
TOPIC_BUTTON = "homeassistant/binary_sensor/pico/button/state"
TOPIC_CONFIG = "homeassistant/binary_sensor/pico_button/config"
# Update the discovery config function
def publish_discovery_config(client):
config = {
"name": "Pico Button",
"state_topic": TOPIC_BUTTON,
"payload_on": "ON",
"payload_off": "OFF",
"unique_id": "pico_button_01",
"device": {
"identifiers": ["pico_sensor_01"],
"name": "Raspberry Pi Pico Sensor",
"model": "Pico",
"manufacturer": "Raspberry Pi Foundation"
}
}
client.publish(TOPIC_CONFIG, json.dumps(config), retain=True)
print("Published button discovery config")
def main():
connect_wifi()
client = connect_mqtt()
publish_discovery_config(client)
button = Pin(0, Pin.IN, Pin.PULL_UP)
last_button_state = button.value()
toggle_state = False
while True:
try:
current_button_state = button.value()
if last_button_state == 1 and current_button_state == 0:
print("Button pressed!")
elif last_button_state == 0 and current_button_state == 1:
print("Button released!")
toggle_state = not toggle_state
if toggle_state:
button_status = "ON"
print("Toggle state: ON")
else:
button_status = "OFF"
print("Toggle state: OFF")
client.publish(TOPIC_BUTTON, button_status)
print(f"Published button state: {button_status}")
last_button_state = current_button_state
time.sleep(0.1) # Check every 100ms for responsiveness
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
if __name__ == "__main__":
main()
5. Test the code by running it from Thonny; your Pico should connect to your Home Assistant.
6. When it's working properly, save it as main.py
Styling with Tailwind CSS
Lorem ipsum dolor sit amet, consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
def hello_world():
print('Hello, world!')