我编写了一个处理MQTT消息(有效负载)的回调函数。我想切换引脚而不是基于传入的有效载荷。我现在遇到的问题是第一个语句在发送11时执行得很好。但是第二个语句不起作用。奇怪的是,当我发送两条包含1x和另一条x1的消息时,我可以再次切换两个引脚。这是一个非常奇怪的问题! 非常感谢任何人都可以帮助我。我正在使用PubSubClient库。
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
//Set GPIO0 to HIGH or LOW on first character received in message
if (payload[0] == '1') {
digitalWrite(GPIO0, HIGH); // Turn the relay on
client.publish(getOutTopic().c_str(), "GPIO0 set to HIGH");
} else if (payload[0] == '0') {
digitalWrite(GPIO0, LOW); // Turn the relay off
client.publish(getOutTopic().c_str(), "GPIO0 set to LOW");
}
//Set GPIO2 to HIGH or LOW on first character received in message
if (payload[1] == '1') {
digitalWrite(GPIO2, HIGH); // turn LED off. With High it is inactive on the ESP-01)
client.publish(getOutTopic().c_str(), "GPIO2 set to HIGH");
} else if (payload[1] == '0') {
digitalWrite(GPIO2, LOW); // Turn the LED on by making the voltage LOW
client.publish(getOutTopic().c_str(), "GPIO2 set to LOW");
}
}
答案 0 :(得分:0)
client.publish破坏有效负载缓冲区。所以我必须将有效载荷捕获到新的变量中才能解决问题。
void callback(char* topic, byte* payload, unsigned int length) {
char p0 = (char)payload[0];
char p1 = (char)payload[1];
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
//Set GPIO0 to HIGH or LOW on first character received in message
if (p0 == '1') {
digitalWrite(GPIO0, HIGH); // Turn the relay on
client.publish(getOutTopic().c_str(), "GPIO0 set to HIGH");
} else if (p0 == '0') {
digitalWrite(GPIO0, LOW); // Turn the relay off
client.publish(getOutTopic().c_str(), "GPIO0 set to LOW");
}
//Set GPIO2 to HIGH or LOW on first character received in message
if (p1 == '1') {
digitalWrite(GPIO2, HIGH); // turn LED off. With High it is inactive on the ESP-01)
client.publish(getOutTopic().c_str(), "GPIO2 set to HIGH");
} else if (p1 == '0') {
digitalWrite(GPIO2, LOW); // Turn the LED on by making the voltage LOW
client.publish(getOutTopic().c_str(), "GPIO2 set to LOW");
}
}