|
发表于 2023-5-10 02:34:15
|
显示全部楼层
esphome:
name: my_relay
platform: ESP8266
board: nodemcuv2
wifi:
ssid: "WiFi名称"
password: "WiFi密码"
# 4路继电器驱动器配置,4路继电器分别连接D1,D2,D3,D4引脚
# 注意,这里的引脚号是ESP8266 GPIO的编号,并非实际的引脚号
# 请参考ESP8266引脚图使用正确的引脚号
output:
- platform: gpio
name: "relay_1"
id: relay_1
pin: D1
- platform: gpio
name: "relay_2"
id: relay_2
pin: D2
- platform: gpio
name: "relay_3"
id: relay_3
pin: D3
- platform: gpio
name: "relay_4"
id: relay_4
pin: D4
# 通过MQTT控制继电器
mqtt:
broker: mqtt_broker_ip_address
username: mqtt_username
password: mqtt_password
# 控制面板,用于在Home Assistant上控制继电器,以及实现状态查询
switch:
- platform: mqtt
name: "relay1"
state_topic: "my_relay/relay1_status"
command_topic: "my_relay/relay1"
qos: 0
- platform: mqtt
name: "relay2"
state_topic: "my_relay/relay2_status"
command_topic: "my_relay/relay2"
qos: 0
- platform: mqtt
name: "relay3"
state_topic: "my_relay/relay3_status"
command_topic: "my_relay/relay3"
qos: 0
- platform: mqtt
name: "relay4"
state_topic: "my_relay/relay4_status"
command_topic: "my_relay/relay4"
qos: 0
# 定义实体状态,传送给Home Assistant
# 这里实现了状态查询功能
interval:
- interval: 1s
then:
- mqtt.publish:
topic: "my_relay/relay1_status"
payload: !lambda |-
if (id(relay_1).state) {
return "ON";
} else {
return "OFF";
}
- mqtt.publish:
topic: "my_relay/relay2_status"
payload: !lambda |-
if (id(relay_2).state) {
return "ON";
} else {
return "OFF";
}
- mqtt.publish:
topic: "my_relay/relay3_status"
payload: !lambda |-
if (id(relay_3).state) {
return "ON";
} else {
return "OFF";
}
- mqtt.publish:
topic: "my_relay/relay4_status"
payload: !lambda |-
if (id(relay_4).state) {
return "ON";
} else {
return "OFF";
}
上述代码中,我们首先配置了WiFi模块的连接和4个继电器驱动器的GPIO引脚等基本设置。接着,我们通过MQTT实现了在Home Assistant中通过MQTT控制继电器的功能。同时,订阅了相关的状态主题信息,用于状态查询。
在使用此代码之前,请根据你使用的芯片型号和引脚连接,进行必要的修改。你还需要根据你的MQTT服务器信息,进行相应的修改。 |
|