Connecting my ESP8266 device to an IOT cloud service. When I push a button in the dashboard, it sends either 1 or 0. Then my ESP should turn a pin HIGH if signal received was 1 or Low if it was 0. Here is the code of the method in question:

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

  if ( (byte)payload[0] == 0) {
    digitalWrite(13, LOW);
    Serial.println("Setting PIN on to LOW");
  } else {
     digitalWrite(13, HIGH);
     Serial.println("Setting PIN off to HIGH");


When sending a 1 signal, serial monitor displays:

Message arrived [/v1.6/devices/esp8266/relay/lv] 1 Setting PIN off to HIGH

When sending a 0 signal, serial monitor displays:

Message arrived [/v1.6/devices/esp8266/relay/lv] 0 Setting PIN off to HIGH

So it seems like it always goes into the else clause. Similarly, if casting the value as char:

if ( (char *)payload[0] == 0) 

Then it will always go into the first condition payload[0] == 0 regardless of the value received.

  • 1
    Is the character you are receiving the number 0 or 1? Or is it the ascii code for the character '0' or '1'? – Delta_G Aug 16 '17 at 5:11
  • 1
    I also can't help but notice that the code you posted is NOT the code that produced the output you posted. Can you please post code and output that actually go together? – Delta_G Aug 16 '17 at 5:12
  • Please, print the length of the payload. – user31481 Aug 16 '17 at 7:48

You receive the character 0 or 1 but compare it to the value 0 or 1. The two things are very different.

You are sending ASCII but comparing it to decimal.

Instead you need to compare like for like. Either:

if (payload[0] == '0') {


if (payload[0] == 48) {

You can find an easy reference for the full ASCII table here.

  • It may be worth noting that the PubSubClient library that appears to be in use here works with strings for payload data, even though the MQTT protocol sends data un-typed (bitstream). (This is not a criticism of the library, as there is quite limited codespace in Arduinos!) – jose can u c Aug 16 '17 at 11:26
  • if (payload[0] == '0') worked out well. Thanks. – Jose Mendez Aug 16 '17 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.