【问题标题】:Start ESP32 when start is published in mqtt在 mqtt 中发布 start 时启动 ESP32
【发布时间】:2022-07-03 14:56:16
【问题描述】:

这是我第一次使用 Arduino、esp32 和 MQTT。我制作了一个运动传感器,当它感应到运动并向 mqtt 发布消息时会打印到 LCD 上,但它会永远循环。我正在尝试使其仅在通过 mqtt 发布 start 时启动,并在发布 stop 时停止。但是,我很难弄清楚。这是我当前的代码(主要部分不包括 MQTT 设置),有人告诉我把它放在回调中可能会有所帮助,但我收到一条错误消息,说“在 '{' 令牌之前不允许函数定义”指使循环无效。任何建议表示赞赏。

void callback(char *topic, byte *payload, unsigned int length) {
 Serial.print("Message arrived in topic: ");
 Serial.println(topic);
 Serial.print("Message:");
 for (int i = 0; i < length; i++) {
     Serial.print((char) payload[i]);
 }
 Serial.println();
 Serial.println("-----------------------");
}

void loop() {
 client.loop();
 
  int motion = digitalRead(sensorPin);
  if (motion == HIGH)
  {
    lcd.setCursor(0, 0);
    lcd.print("!!!!!MOTION!!!!!");
   client.publish(topic, "MOTION");
        delay(100);
}
else
{
   lcd.setCursor(0, 0);
    lcd.print("   no  motion   ");
   client.publish(topic, "NO MOTION");
       delay(500);

}
}

【问题讨论】:

  • 向我们展示您的尝试;将代码添加到callback 以处理消息并设置标志应该相对简单(您还需要subscribe 到主题)。

标签: c arduino mqtt esp32 arduino-esp32


【解决方案1】:

首先:当检测到运动时,为什么要在 mqtt 上无限次发布? 您检测到动作(digitalRead),发布它(即使用retain=true),一旦发布,设置标志,即published=true。存储运动的先前状态并且在它改变之前不要发布(从运动到无运动,反之亦然)。 当检测到运动 (client.publish(topic, "MOTION");) 或清除运动 (client.publish(topic, "NO MOTION");) 时,您的代码将永远发布。

如果我理解正确:您只想在 MQTT 上的消息出现时发布运动状态:“开始检查运动”,对吗? 如果是这样,在回调中,您在消息到达时更改全局变量,即“start_checking_motion = true”(在 MQTT 上的命令之前将其设置为 false) 然后在循环中,首先您要做的是检查 start_checking_motion == true - 如果是,则执行动作检查并发布 - 但同样:仅当动作发生变化时 - 请参阅我帖子的第一段

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2021-03-20
    • 1970-01-01
    • 2019-02-23
    • 2021-05-03
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多