MQTT & ESP8266

New user having used this place extensively, so thank you for all you’ve already taught me and apologies if this isn’t the right place for this - I’m very much still learning.

Currently trying to work out MQTT and the ESP01 bit just controlling the onboard LED. Using CloudMQTT this sketch works perfectly, except the LED initially is on and the commands are switched - “ON,” turns it off and vice versa. I’ve tried all the things I can think of and tinkered with the code, but can anyone figure out where on Earth I’m going wrong?

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid         = "SSID";
const char* password     = "Password";
const char* mqttServer   = "";
const int   mqttPort     = portNo;
const char* mqttUser     = "User";
const char* mqttPassword = "Password";

#define PUB_GPIO2_STATUS "esp8266/gpio2/status"
#define SUB_GPIO2_ACTION "esp8266/gpio2/action"

const short int GPIO2_LED = 1;

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

void setup() {

    pinMode(GPIO2_LED, OUTPUT);


void loop() {


void initWifiStation() {

    WiFi.begin(ssid, password);    
void initMQTTClient() {

    mqttClient.setServer(mqttServer, mqttPort);

    // Declare Pub/Sub topics
    mqttClient.publish(PUB_GPIO2_STATUS, "OFF");
void PubSubCallback(char* topic, byte* payload, unsigned int length) {

    String strTopicGpio2Action = SUB_GPIO2_ACTION;
    String strPayload = "";
    String strON = "ON";
    String strOFF = "OFF";
    if (strTopicGpio2Action == topic) {
        if (strON == strPayload) {
            digitalWrite(GPIO2_LED, HIGH);
            mqttClient.publish(PUB_GPIO2_STATUS, "ON");
        } else if (strOFF == strPayload) {
            digitalWrite(GPIO2_LED, LOW);
            mqttClient.publish(PUB_GPIO2_STATUS, "OFF");


How is the LED wired?

IIRC the LED is wired to the ESP8266 pin for input (the ESP sinks the current flow) so pulling the pin low turns it on and high turns it off.