【发布时间】: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