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.
| Topic | Direction | Payload | Retained |
|---|---|---|---|
solderhub/lab/relaybox01/command/channel/1 … /8 | Dashboard → ESP32 | ON / OFF | No |
solderhub/lab/relaybox01/command/all | Dashboard → ESP32 | OFF (all channels off) | No |
solderhub/lab/relaybox01/state/channel/1 … /8 | ESP32 → everyone | ON / OFF | Yes |
solderhub/lab/relaybox01/status | ESP32 (and broker via Last Will) | online / offline | Yes |
1. Why this topic design
- One topic per channel makes permissions simple (an account can be allowed
command/channel/1only), and anyone can subscribe tostate/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 pin | ESP32 GPIO | Why this pin |
|---|---|---|
| IN1 | GPIO32 | No boot-strapping role |
| IN2 | GPIO33 | No boot-strapping role |
| IN3 | GPIO25 | No boot-strapping role |
| IN4 | GPIO26 | No boot-strapping role |
| IN5 | GPIO27 | No boot-strapping role |
| IN6 | GPIO23 | No boot-strapping role |
| IN7 | GPIO22 | Free if you don't use I2C |
| IN8 | GPIO21 | Free if you don't use I2C |
| VCC | 3V3 (with JD-VCC jumper removed) | Input side at ESP32 logic level |
| JD-VCC | External 5 V supply + | Powers the relay coils |
| GND | ESP32 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.
#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
| Part | Why 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 : HIGH | One flag for active-low or active-high boards |
strtol + range check on the channel | A topic like …/channel/9 or …/channel/abc is ignored instead of indexing past the array |
strcasecmp on a small buffer | Accepts 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)connect | Dashboards resync after outages without guessing |
command/all accepts only OFF | A 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:
mosquitto_sub -h 192.168.1.50 -u nodered -P 'YOUR_PASSWORD' -t 'solderhub/lab/relaybox01/#' -vSwitch channel 3 on and off, then all off:
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| Test | Expected result |
|---|---|
| Power up | No relay clicks; status online and eight retained OFF states |
channel/3 ON | Relay 3 clicks; state/channel/3 ON |
| Send ON twice | Stays on; state published twice, no toggling |
channel/9 or payload TOGGLE | Ignored; Serial shows why |
| Unplug the ESP32 | ~20 s later the broker publishes status offline |
| Restart the broker | ESP32 reconnects and republishes all eight states |
| Subscribe from a new terminal | Immediately 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 writestate/#andstatusonly. - 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Relays click briefly at boot | Strapping pins that toggle during boot, or pinMode(OUTPUT) called before the OFF level was written | Use the listed GPIOs; keep the OFF-before-pinMode order |
| Relays never release / LEDs glow dimly | Input side on 5 V with 3.3 V logic | Remove the JD-VCC jumper; VCC from 3V3, JD-VCC from 5 V |
| ESP32 resets when several relays switch | Coils powered from the ESP32's 5 V/USB | Separate 5 V supply on JD-VCC, common GND |
| Commands ignored | Topic typo or wrong case, or payload has a trailing newline | Watch with mosquitto_sub -v; the sketch accepts ON/OFF only |
MQTT failed, rc=5 | Wrong user/password or ACL | Check mosquitto_passwd and the ACL file |
rc=-2 | Broker unreachable | See MQTT troubleshooting |
| Relay switches on after reconnect | A retained command on the broker | Clear it: mosquitto_pub -t '…/command/channel/N' -r -n |
| Wrong relay switches | GPIO order differs from IN labels | Fix 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
- Node-RED 8-channel relay dashboard: eight switches that follow the reported state.
- ESP32 MQTT retained messages and Last Will.
- Non-blocking MQTT auto-reconnect on ESP32.
- MQTT explained: QoS, retained and LWT.
- Cloud alternative: Blynk relay control with ESP32.




