使用 433MHz 发射模块控制遥控卷叶门并接入HA

发布于 2020-05-07   71 次阅读   Home Assistant


需要具备的条件:

  • 已安装 HA
  • 已安装 MQTT
  • 已安装 Node-RED
  • 懂得基本的 Arduino 开发板烧录

需要准备的材料:

  • 433MHz 发射模块 * 1
  • 433MHz 接收模块 * 1
  • ESP8266 NodeMcu Lua WiFi V3 物联网开发板 * 1
  • 3.3v 电源模块 *1
  • 电源 * 1
  • 杜邦线 * N
  • 三色LED灯珠 * 1
  • 外壳 * 1
我正好有个坏了的路由器,我就拿这个做外壳了。
这个433MHz模块的天线被我剪断了重新接的,变形了不影响使用。

下载相关文件:

1、获取遥控代码

接线图:

打开示例:

打开示例并烧录到开发板 文件 - 示例 - rc-switch - ReceiveDemo_Advanced

打开串口,按遥控器按键:

【串口返回数据】
二进制代码:001000101100010010010100
协议:Protocol: 1
脉冲长度:PulseLength: 262

Decimal: 705748 (24Bit) Binary: 001000101100010010010100 Tri-State: not applicable PulseLength: 262 microseconds Protocol: 1
Raw data: 8136,180,860,184,864,180,860,184,860,712,340,188,860,712,340,188,864,712,340,712,348,180,868,180,868,176,868,708,344,180,872,176,864,708,348,716,336,184,864,712,340,184,868,708,344,184,864,180,868,

2、烧录主程序

#include <Ticker.h>
#include <EEPROM.h>
#include <RCSwitch.h>
#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define LED D4                                             // 板载指示灯端口
#define LEDR D5                                            // 红色指示灯端口
#define LEDG D7                                            // 绿色指示灯端口
#define LEDB D8                                            // 蓝色指示灯端口
#define MQTT_CLIENT     "NodeMCU V3"                       // MQTT客户端名称
#define MQTT_SERVER     ""                                 // MQTT服务器IP
#define MQTT_PORT       1883                               // MQTT服务器端口
#define MQTT_TOPIC      "home/芯片ID"                      // MQTT连接主题
#define MQTT_USER       ""                                 // MQTT服务器用户名
#define MQTT_PASS       ""                                 // MQTT服务器的密码
#define WIFI_SSID       ""                                 // WiFi SSID
#define WIFI_PASS       ""                                 // WiFi Password
#define HEARTBEAT_S     60                                 // 心跳检查 (单位:秒)

#define VERSION    "\n\n===================================================\n            433MHz模块 & MQTT 通讯示例             \n                    作者:旋风                    \n                     33m.me                      \n===================================================\n\n"

bool RequestRestart = false;

extern "C" {
  #include "user_interface.h"
}

int UpdFreq = 1;  // 频率
int Retries = 20; // 重试次数

unsigned long TTasks;

WiFiClient WiFiClient;
RCSwitch Switch = RCSwitch();
PubSubClient MQTTClient(WiFiClient, MQTT_SERVER, MQTT_PORT);


void setup() {
  // 初始化
  pinMode(LED, OUTPUT);
  pinMode(LEDR, OUTPUT);
  pinMode(LEDG, OUTPUT);
  pinMode(LEDB, OUTPUT);
  digitalWrite(LED, 1);
  digitalWrite(LEDR, 0);
  digitalWrite(LEDG, 0);
  digitalWrite(LEDB, 0);
  
  MQTTClient.set_callback(callback);
  // 设置引脚 #D6
  Switch.enableTransmit(D6);
  // 设置协议(默认为1,适用于大多数设备)
  Switch.setProtocol(1);
  // 设置脉冲长度
  Switch.setPulseLength(263);
  
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.begin(115200);
  Serial.println(VERSION);
  Serial.print("\nESP芯片ID: ");
  Serial.print(ESP.getChipId(), HEX);
  Serial.print("\n正在连接到WiFi: "); Serial.print(WIFI_SSID); Serial.print(" . . ."); 
  while ((WiFi.status() != WL_CONNECTED) && Retries --) {
    digitalWrite(LEDB, !digitalRead(LEDB));
    delay(500);
    Serial.print(" .");
    
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println(" 成功");
    Serial.print("当前设备内网IP: "); Serial.println(WiFi.localIP());
    Serial.print("正在连接到MQTT服务器: ");Serial.print(MQTT_SERVER);Serial.print(" . . .");
    delay(500);
    while (!MQTTClient.connect(MQTT::Connect(MQTT_CLIENT).set_keepalive(90).set_auth(MQTT_USER, MQTT_PASS)) && Retries --) {
      digitalWrite(LEDB, !digitalRead(LEDB));
      Serial.print(" .");
      delay(1000);
    }
    if(MQTTClient.connected()) {
      Serial.println(" 成功");
      Serial.println("\n------------------------- 日志 -------------------------");
      Serial.println();
      digitalWrite(LEDR, 0);
      digitalWrite(LEDG, 1);
      digitalWrite(LEDB, 0);
      MQTTClient.publish(MQTT::Publish(MQTT_TOPIC, "state").set_retain().set_qos(2));
      MQTTClient.subscribe(MQTT_TOPIC);
      BlinkLED(LEDB, 50, 5);
    }
    else {
      digitalWrite(LEDR, 1);
      digitalWrite(LEDG, 0);
      digitalWrite(LEDB, 0);
      Serial.println(" 失败 (等待自动重启...)");
      Serial.println("\n-------------------------------------------------------");
      Serial.println();
    }
  }
  else {
    digitalWrite(LEDR, 1);
    digitalWrite(LEDG, 0);
    digitalWrite(LEDB, 0);
    Serial.println(" 失败 (等待自动重启...)");
    Serial.println("\n-------------------------------------------------------");
    Serial.println();
  }
}

void loop() {
  // 循环
  MQTTClient.loop();
  TimedTasks();
  
  /*重启-板载LED闪烁*/
  if (RequestRestart) {
    Serial.println("网络连接异常,即将重启...");
    BlinkLED(LEDB, 60, 5);
    ESP.restart();
  }
}


/*MQTT控制*/
void callback(const MQTT::Publish& pub) {
  if (pub.payload_string() == "state") {
  }
  else if (pub.payload_string() == "1") {
    // 开门
    Switch.send("00000开门代码00000");
    MQTTClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", "1").set_retain().set_qos(2));
    BlinkLED(LEDB, 500, 1);
  }
  else if (pub.payload_string() == "2") {
    // 关门
    Switch.send("00000关门代码00000");
    MQTTClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", "2").set_retain().set_qos(2));
    BlinkLED(LEDB, 500, 1);
  }
  else if (pub.payload_string() == "3") {
    // 上锁
    Switch.send("00000上锁代码00000");
    MQTTClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", "3").set_retain().set_qos(2));
    BlinkLED(LEDB, 500, 1);
  }
  else if (pub.payload_string() == "4") {
    // 停止/解锁
    Switch.send("00000停止代码00000");
    MQTTClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", "4").set_retain().set_qos(2));
    BlinkLED(LEDB, 500, 1);
  }
  else if (pub.payload_string() == "reset") {
    RequestRestart = true;
  }
  delay(100);
}

/*定时任务-心跳检查*/
void TimedTasks() {
  if ((millis() > TTasks + (UpdFreq*1000*HEARTBEAT_S)) || (millis() < TTasks)) { 
    TTasks = millis();
    CheckConnection();
  }
}

/*心跳检查*/
void CheckConnection() {
  if (WiFi.status() == WL_CONNECTED)  {
    if (MQTTClient.connected()) {
      Serial.println("[心跳检查]MQTT服务器连接 . . . . . . . . . . 正常");
      digitalWrite(LEDR, 0);
      digitalWrite(LEDG, 1);
      digitalWrite(LEDB, 0);
    } 
    else {
      Serial.println("[心跳检查]MQTT服务器连接 . . . . . . . . . . 离线");
      digitalWrite(LEDR, 1);
      digitalWrite(LEDG, 0);
      digitalWrite(LEDB, 0);
      RequestRestart = true;
    }
  }
  else {
    Serial.println("[心跳检查] WiFi连接 . . . . . . . . . . 离线");
    digitalWrite(LEDR, 1);
    digitalWrite(LEDG, 0);
    digitalWrite(LEDB, 0);
    RequestRestart = true;
  }
}

/*闪烁LED*/
void BlinkLED(int pin, int Duration, int n) {
  for(int i=0; i<n; i++){
    digitalWrite(pin, !digitalRead(pin));
    delay(Duration);
    digitalWrite(pin, !digitalRead(pin));
    delay(Duration);
  }
}

接线图:

由于没找到那个型号的模板,就用这个代替了,这个板子也是一样的。

HA配置:

switch:
# 开关
  # MQTT
  - platform: mqtt
    name: "开门"
    state_topic: "home/芯片ID/stat"
    command_topic: "home/芯片ID"
    qos: 2
    payload_on: "1"
    payload_off: "1ok"
    retain: true
  - platform: mqtt
    name: "关门"
    state_topic: "home/芯片ID/stat"
    command_topic: "home/芯片ID"
    qos: 2
    payload_on: "2"
    payload_off: "2ok"
    retain: true
  - platform: mqtt
    name: "上锁"
    state_topic: "home/芯片ID/stat"
    command_topic: "home/芯片ID"
    qos: 2
    payload_on: "3"
    payload_off: "3ok"
    retain: true
  - platform: mqtt
    name: "停止/解锁"
    state_topic: "home/芯片ID/stat"
    command_topic: "home/芯片ID"
    qos: 2
    payload_on: "4"
    payload_off: "4ok"
    retain: true
sensor:
# 传感器
  # MQTT
  - platform: mqtt
    state_topic: "home/芯片ID/S"
    name: "状态"

Node-RED代码:

[{"id":"55aecad4.b16c44","type":"tab","label":"433MHz&MQTT","disabled":false,"info":""},{"id":"bf8cd04f.54ca6","type":"mqtt in","z":"55aecad4.b16c44","name":"","topic":"home/芯片ID/stat","qos":"2","datatype":"auto","broker":"667f2faa.b213d","x":130,"y":160,"wires":[["fe886335.cf80a"]]},{"id":"ec66a736.ad2ea8","type":"mqtt out","z":"55aecad4.b16c44","name":"","topic":"home/芯片ID/stat","qos":"2","retain":"","broker":"667f2faa.b213d","x":830,"y":160,"wires":[]},{"id":"fe886335.cf80a","type":"switch","z":"55aecad4.b16c44","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"1","vt":"str"},{"t":"eq","v":"2","vt":"str"},{"t":"eq","v":"3","vt":"str"},{"t":"eq","v":"4","vt":"str"}],"checkall":"true","repair":false,"outputs":4,"x":290,"y":160,"wires":[["2958d9dd.557296","36cb33a0.1a6cac"],["c006221b.311d5","36cb33a0.1a6cac"],["b752d220.03b77","36cb33a0.1a6cac"],["1bf400e1.6c777f","36cb33a0.1a6cac"]]},{"id":"2958d9dd.557296","type":"delay","z":"55aecad4.b16c44","name":"","pauseType":"delay","timeout":"1","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":440,"y":100,"wires":[["83c81917.fe7fb8"]]},{"id":"83c81917.fe7fb8","type":"change","z":"55aecad4.b16c44","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"1ok","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":610,"y":100,"wires":[["ec66a736.ad2ea8"]]},{"id":"c006221b.311d5","type":"delay","z":"55aecad4.b16c44","name":"","pauseType":"delay","timeout":"1","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":440,"y":140,"wires":[["78892980.03f438"]]},{"id":"78892980.03f438","type":"change","z":"55aecad4.b16c44","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"2ok","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":610,"y":140,"wires":[["ec66a736.ad2ea8"]]},{"id":"b752d220.03b77","type":"delay","z":"55aecad4.b16c44","name":"","pauseType":"delay","timeout":"1","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":440,"y":180,"wires":[["6e1c5544.21776c"]]},{"id":"6e1c5544.21776c","type":"change","z":"55aecad4.b16c44","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"3ok","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":610,"y":180,"wires":[["ec66a736.ad2ea8"]]},{"id":"1bf400e1.6c777f","type":"delay","z":"55aecad4.b16c44","name":"","pauseType":"delay","timeout":"1","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":440,"y":220,"wires":[["97638d12.e04b3"]]},{"id":"97638d12.e04b3","type":"change","z":"55aecad4.b16c44","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"4ok","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":610,"y":220,"wires":[["ec66a736.ad2ea8"]]},{"id":"9f0b007d.4978d","type":"ping","z":"55aecad4.b16c44","mode":"triggered","name":"Ping","host":"设备局域网IP","timer":"60","inputs":1,"x":430,"y":360,"wires":[["c11b1e92.9b023"]]},{"id":"c11b1e92.9b023","type":"switch","z":"55aecad4.b16c44","name":"","property":"payload","propertyType":"msg","rules":[{"t":"istype","v":"number","vt":"number"},{"t":"false"}],"checkall":"true","repair":false,"outputs":2,"x":550,"y":360,"wires":[["2ab9b998.0a4506"],["8e534d0a.165f"]]},{"id":"2038a8fd.30f9a8","type":"mqtt out","z":"55aecad4.b16c44","name":"","topic":"home/芯片ID/S","qos":"","retain":"","broker":"667f2faa.b213d","x":830,"y":360,"wires":[]},{"id":"2ab9b998.0a4506","type":"change","z":"55aecad4.b16c44","name":"在线","rules":[{"t":"set","p":"payload","pt":"msg","to":"在线","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":670,"y":340,"wires":[["2038a8fd.30f9a8"]]},{"id":"8e534d0a.165f","type":"change","z":"55aecad4.b16c44","name":"离线","rules":[{"t":"set","p":"payload","pt":"msg","to":"离线","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":670,"y":380,"wires":[["2038a8fd.30f9a8"]]},{"id":"36cb33a0.1a6cac","type":"change","z":"55aecad4.b16c44","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"设备局域网IP","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":470,"y":280,"wires":[["9f0b007d.4978d"]]},{"id":"72e1a885.0fedb8","type":"mqtt in","z":"55aecad4.b16c44","name":"","topic":"home/芯片ID","qos":"2","datatype":"auto","broker":"667f2faa.b213d","x":120,"y":200,"wires":[["20ad313.7a960ce"]]},{"id":"20ad313.7a960ce","type":"switch","z":"55aecad4.b16c44","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"1","vt":"str"},{"t":"eq","v":"2","vt":"str"},{"t":"eq","v":"3","vt":"str"},{"t":"eq","v":"4","vt":"str"}],"checkall":"true","repair":false,"outputs":4,"x":270,"y":240,"wires":[["36cb33a0.1a6cac"],["36cb33a0.1a6cac"],["36cb33a0.1a6cac"],["36cb33a0.1a6cac"]]},{"id":"7d93246.7cfe9dc","type":"ping","z":"55aecad4.b16c44","mode":"timed","name":"定时Ping","host":"设备局域网IP","timer":"3","inputs":0,"x":420,"y":400,"wires":[["c11b1e92.9b023"]]},{"id":"667f2faa.b213d","type":"mqtt-broker","z":"","name":"","broker":"MQTT地址","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""}]