Skip to content

Tutorial

ESP32 8-Channel Relay over MQTT with State Feedback (Full Code)

Drive an 8-channel relay board from MQTT with an ESP32: topic design, safe wiring and power, a complete sketch with retained state and Last Will, tests and fixes.

  • 4 min read
  • Updated November 2, 2026
ESP32 8-Channel Relay over MQTT with State Feedback (Full Code)

Quick answer: to control an 8-channel relay board with an ESP32 over MQTT, subscribe the ESP32 to solderhub/lab/relaybox01/command/channel/+. In the callback, read the channel number from the end of the topic, accept only ON or OFF, drive the matching GPIO (LOW = ON on most relay boards), then publish the applied state, retained, to …/state/channel/N. Set every relay OFF before Wi-Fi starts, register a Last Will on …/status so dashboards know when the box goes offline, and power the relay coils from a separate 5 V supply. The complete, tested-pattern sketch is below.

An MQTT command saying ON is a request; the state topic is the board's report of what it actually did. Keeping those separate is what makes a dashboard trustworthy after Wi-Fi drops, reboots and duplicate messages. The Node-RED 8-channel relay dashboard uses exactly this topic layout, so the two guides work together.

TopicDirectionPayloadRetained
solderhub/lab/relaybox01/command/channel/1 … /8Dashboard → ESP32ON / OFFNo
solderhub/lab/relaybox01/command/allDashboard → ESP32OFF (all channels off)No
solderhub/lab/relaybox01/state/channel/1 … /8ESP32 → everyoneON / OFFYes
solderhub/lab/relaybox01/statusESP32 (and broker via Last Will)online / offlineYes

1. Why this topic design

  • One topic per channel makes permissions simple (an account can be allowed command/channel/1 only), and anyone can subscribe to state/channel/+ to watch everything.
  • Explicit ON/OFF, never TOGGLE. If a message is delivered twice (QoS 1 can do that) or a dashboard retries, a repeated ON is harmless, while a repeated TOGGLE switches the load back off.
  • Commands are never retained. A retained ON would be replayed every time the ESP32 reconnects, possibly hours later, switching a heater or pump on by surprise.
  • State is retained, so a dashboard opened later instantly shows the real state of all eight channels.
  • Status uses Last Will, so "offline" is published by the broker even if the ESP32 loses power.

More on naming: MQTT topic naming best practices. More on retained messages and Last Will: ESP32 MQTT retained messages and LWT.

2. Wire the 8-channel relay board

Relay board pinESP32 GPIOWhy this pin
IN1GPIO32No boot-strapping role
IN2GPIO33No boot-strapping role
IN3GPIO25No boot-strapping role
IN4GPIO26No boot-strapping role
IN5GPIO27No boot-strapping role
IN6GPIO23No boot-strapping role
IN7GPIO22Free if you don't use I2C
IN8GPIO21Free if you don't use I2C
VCC3V3 (with JD-VCC jumper removed)Input side at ESP32 logic level
JD-VCCExternal 5 V supply +Powers the relay coils
GNDESP32 GND and 5 V supply −Common reference for the inputs

Avoid GPIO0, 2, 5, 12 and 15 (boot-strapping), 6–11 (flash) and 34–39 (input-only). See the ESP32 pinout guide.

Power: each energised coil draws roughly 70–90 mA at 5 V, so all eight on is around 0.6–0.7 A, far more than the ESP32's USB pin should supply. Use a separate 5 V 1–2 A supply on JD-VCC with the jumper removed. With the jumper removed and VCC on 3V3, the optocoupler inputs also switch fully off at the ESP32's 3.3 V HIGH level, which avoids the common "relay never releases" problem of 5 V-only input wiring.

Most of these boards are active-low (IN LOW = relay ON). Confirm yours: with power applied, touch one IN pin to GND and the relay should click.

Mains safety: test with LEDs or a 12 V lamp first. Mains loads need correctly rated relays, an enclosure, fusing and proper clearances; where required, have the installation done by a qualified electrician. Never put mains wiring on a breadboard.

3. The complete ESP32 sketch

Install PubSubClient (Nick O'Leary) from the Library Manager, fill in Wi-Fi and broker details, and upload. The sketch:

  • sets all relays OFF before Wi-Fi starts;
  • connects with a Last Will (status = offline, retained);
  • subscribes to every channel with one wildcard;
  • validates the channel number and payload, applies it, and publishes the retained state;
  • republishes all eight states after every reconnect;
  • never blocks loop(), retrying Wi-Fi/MQTT every 5 seconds.
sketch.ino
#include <WiFi.h>
#include <PubSubClient.h>

// ---------- Settings ----------
const char* WIFI_SSID = "REPLACE_WITH_WIFI";
const char* WIFI_PASS = "REPLACE_WITH_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.50";
const uint16_t MQTT_PORT = 1883;
const char* MQTT_USER = "relaybox01";
const char* MQTT_PASS = "REPLACE_WITH_MQTT_PASSWORD";
const char* CLIENT_ID = "solderhub-relaybox01";
const char* BASE      = "solderhub/lab/relaybox01";

const uint8_t NUM_CH = 8;
const uint8_t RELAY_PINS[NUM_CH] = {32, 33, 25, 26, 27, 23, 22, 21};
const bool    ACTIVE_LOW = true;          // most relay boards: LOW = ON

WiFiClient net;
PubSubClient mqtt(net);
bool state[NUM_CH] = {false};
unsigned long lastAttempt = 0;

void writePin(uint8_t i, bool on) {
  digitalWrite(RELAY_PINS[i], (on == ACTIVE_LOW) ? LOW : HIGH);
}

void publishState(uint8_t i) {
  char topic[80];
  snprintf(topic, sizeof(topic), "%s/state/channel/%u", BASE, i + 1);
  mqtt.publish(topic, state[i] ? "ON" : "OFF", true);   // retained
}

void setChannel(uint8_t i, bool on) {
  state[i] = on;
  writePin(i, on);
  publishState(i);
  Serial.printf("CH%u -> %s\n", i + 1, on ? "ON" : "OFF");
}

void onMessage(char* topic, byte* payload, unsigned int len) {
  char msg[8];
  if (len == 0 || len >= sizeof(msg)) return;
  memcpy(msg, payload, len);
  msg[len] = '\0';
  bool on;
  if (strcasecmp(msg, "ON") == 0) on = true;
  else if (strcasecmp(msg, "OFF") == 0) on = false;
  else { Serial.printf("Ignored payload '%s'\n", msg); return; }

  char allTopic[80];
  snprintf(allTopic, sizeof(allTopic), "%s/command/all", BASE);
  if (strcmp(topic, allTopic) == 0) {                    // "all" accepts OFF only
    if (!on) for (uint8_t i = 0; i < NUM_CH; i++) setChannel(i, false);
    return;
  }

  const char* last = strrchr(topic, '/');               // ".../channel/3" -> "3"
  if (!last) return;
  char* end;
  long ch = strtol(last + 1, &end, 10);
  if (*end != '\0' || ch < 1 || ch > NUM_CH) { Serial.println("Bad channel"); return; }
  setChannel(ch - 1, on);
}

void connectMqtt() {
  char statusTopic[80], cmdTopic[80], allTopic[80];
  snprintf(statusTopic, sizeof(statusTopic), "%s/status", BASE);
  snprintf(cmdTopic, sizeof(cmdTopic), "%s/command/channel/+", BASE);
  snprintf(allTopic, sizeof(allTopic), "%s/command/all", BASE);

  if (mqtt.connect(CLIENT_ID, MQTT_USER, MQTT_PASS, statusTopic, 1, true, "offline")) {
    mqtt.publish(statusTopic, "online", true);
    mqtt.subscribe(cmdTopic, 1);
    mqtt.subscribe(allTopic, 1);
    for (uint8_t i = 0; i < NUM_CH; i++) publishState(i);   // board is the source of truth
    Serial.println("MQTT connected");
  } else {
    Serial.printf("MQTT failed, rc=%d\n", mqtt.state());
  }
}

void setup() {
  // 1) Safe state before anything else
  for (uint8_t i = 0; i < NUM_CH; i++) {
    writePin(i, false);
    pinMode(RELAY_PINS[i], OUTPUT);
  }
  Serial.begin(115200);

  // 2) Networking (non-blocking)
  WiFi.mode(WIFI_STA);
  WiFi.setAutoReconnect(true);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (WiFi.status() == WL_CONNECTED && !mqtt.connected() && millis() - lastAttempt > 5000) {
    lastAttempt = millis();
    connectMqtt();
  }
  mqtt.loop();
}

Key details in the code

PartWhy it matters
writePin(i, false) before pinMode(OUTPUT)Each pin's first output level is OFF, so no relay clicks at power-up
(on == ACTIVE_LOW) ? LOW : HIGHOne flag for active-low or active-high boards
strtol + range check on the channelA topic like …/channel/9 or …/channel/abc is ignored instead of indexing past the array
strcasecmp on a small bufferAccepts on/ON, rejects anything else, no String heap churn
subscribe(..., 1)QoS 1 for commands: delivered at least once, and duplicates are harmless with ON/OFF
Publish all states on (re)connectDashboards resync after outages without guessing
command/all accepts only OFFA one-tap "everything off" is useful; "everything on" is rarely safe

The state topic reports the GPIO level the firmware applied. To prove a load really switched (contacts welded, fuse blown, no mains present), you need feedback hardware such as a current sensor or an auxiliary contact on a spare input, published on its own topic.

4. Test it from the command line

Watch everything the box publishes:

terminal
mosquitto_sub -h 192.168.1.50 -u nodered -P 'YOUR_PASSWORD' -t 'solderhub/lab/relaybox01/#' -v

Switch channel 3 on and off, then all off:

terminal
mosquitto_pub -h 192.168.1.50 -u nodered -P 'YOUR_PASSWORD' -t 'solderhub/lab/relaybox01/command/channel/3' -m ON
mosquitto_pub -h 192.168.1.50 -u nodered -P 'YOUR_PASSWORD' -t 'solderhub/lab/relaybox01/command/channel/3' -m OFF
mosquitto_pub -h 192.168.1.50 -u nodered -P 'YOUR_PASSWORD' -t 'solderhub/lab/relaybox01/command/all' -m OFF
TestExpected result
Power upNo relay clicks; status online and eight retained OFF states
channel/3 ONRelay 3 clicks; state/channel/3 ON
Send ON twiceStays on; state published twice, no toggling
channel/9 or payload TOGGLEIgnored; Serial shows why
Unplug the ESP32~20 s later the broker publishes status offline
Restart the brokerESP32 reconnects and republishes all eight states
Subscribe from a new terminalImmediately receives all eight retained states

New to the command-line clients? See Test MQTT without hardware.

5. Lock it down

  • Give the relay box its own MQTT user and an ACL that lets it read solderhub/lab/relaybox01/command/# and write state/# and status only.
  • Give dashboards write access to the command topics; give sensors no access to them at all.
  • Keep the broker on your LAN or VPN, with TLS if traffic crosses networks you don't control. Setup: Secure Node-RED and Mosquitto.
  • Keep a local, physical way to switch critical loads off. A dashboard is not an emergency stop.

Troubleshooting

SymptomLikely causeFix
Relays click briefly at bootStrapping pins that toggle during boot, or pinMode(OUTPUT) called before the OFF level was writtenUse the listed GPIOs; keep the OFF-before-pinMode order
Relays never release / LEDs glow dimlyInput side on 5 V with 3.3 V logicRemove the JD-VCC jumper; VCC from 3V3, JD-VCC from 5 V
ESP32 resets when several relays switchCoils powered from the ESP32's 5 V/USBSeparate 5 V supply on JD-VCC, common GND
Commands ignoredTopic typo or wrong case, or payload has a trailing newlineWatch with mosquitto_sub -v; the sketch accepts ON/OFF only
MQTT failed, rc=5Wrong user/password or ACLCheck mosquitto_passwd and the ACL file
rc=-2Broker unreachableSee MQTT troubleshooting
Relay switches on after reconnectA retained command on the brokerClear it: mosquitto_pub -t '…/command/channel/N' -r -n
Wrong relay switchesGPIO order differs from IN labelsFix the order in RELAY_PINS

FAQ

Can I use fewer than 8 relays? Yes. Change NUM_CH and the RELAY_PINS array. Everything else adapts.

Should the relay restore its last state after a power cut? Only for harmless loads. This sketch boots OFF and reports OFF. To restore, keep a "desired state" on a separate retained topic, or in NVS with the Preferences library, and apply it deliberately in setup().

Why QoS 1 and not 2? PubSubClient subscribes at QoS 0 or 1, and with explicit ON/OFF payloads a duplicate delivery does no harm, so QoS 1 is enough.

Can Home Assistant control this? Yes. Use MQTT switch entities with command_topic = …/command/channel/N, state_topic = …/state/channel/N, payload_on: "ON", payload_off: "OFF" and availability_topic = …/status.

Next steps

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.