• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

MQTT Relay Driver – Wont drive relays

Q&A Forum › Category: Home Automation › MQTT Relay Driver – Wont drive relays
0 Vote Up Vote Down
Mark Bolton asked 4 years ago

I have fixed it…. I couldn’t see for staring  too hard…. I had commented out half the driving code….

I am a n00b at code modifying.
The hardware all works since I modded the code with the Web Server version of this and the switching from the browser work and I assume the names assigned to the variable do also. Just there is no drive to the relay module. They remain ON.
Could some one be so kind as to cast an eye over the code I have modified to see if there is any thing glaringly wrong with it ?
TIA
Mark

Serial Monitor Output
……………………………………………………………………………………………………………………………..
Publishing on topic esp32/temperature at QoS 2, packetId: 283
Publish acknowledged.
packetId: 283
Publish received.
message: 1off
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 4
index: 0
total: 4
Publish received.
message: 2off
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 4
index: 0
total: 4
Publish received.
message: 3off
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 4
index: 0
total: 4
Publish received.
message: 4off
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 4
index: 0
total: 4
Publish received.
message: 1on
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 3
index: 0
total: 3
Publish received.
message: 2on
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 3
index: 0
total: 3
Publish received.
message: 3on
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 3
index: 0
total: 3
Publish received.
message: 4on
topic: esp32/relay
qos: 0
dup: 0
retain: 0
len: 3
index: 0
total: 3
Publishing on topic esp32/temperature at QoS 2, packetId: 284
Publish acknowledged.
packetId: 284
…………………………………………………………………………………………………………………………………………………..
/*********
MQTT Relay Driver
Rui Santos
Complete project details at https://randomnerdtutorials.com

Ref: Learning ESP32 with ArduinoIDE page 358

Modified to remove push button and to add 4 relays instead of the LED – Mark Bolton September 28 2021
*********/
#include <WiFi.h>
extern “C” {
#include “freertos/FreeRTOS.h”
#include “freertos/timers.h”
}
#include <AsyncMqttClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Change the credentials below, so your ESP32 connects to your router
#define WIFI_SSID “Mark_Network”
#define WIFI_PASSWORD “er1amjhwif”
// Change the MQTT_HOST variable to your Raspberry Pi IP address,
// so it connects to your Mosquitto MQTT broker
#define MQTT_HOST IPAddress(192, 168, 1, 105)
#define MQTT_PORT 1883
// Create objects to handle MQTT client
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // interval at which to publish sensor readings
// Assign output variables to GPIO pins
const int output25 = 25; // GPIO where the Relay is connected to
const int output26 = 26;
const int output27 = 27;
const int output33 = 33;
// GPIO where the DS18B20 is connected to
const int oneWireBus = 32; // was 27 ADDED
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
void connectToWifi() {
Serial.println(“Connecting to Wi-Fi…”);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt() {
Serial.println(“Connecting to MQTT…”);
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf(“[WiFi-event] event: %d\n”, event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println(“WiFi lost connection”);
xTimerStop(mqttReconnectTimer, 0); // ensure we don’t reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
// Add more topics that want your ESP32 to be subscribed to
void onMqttConnect(bool sessionPresent) {
Serial.println(“Connected to MQTT.”);
Serial.print(“Session present: “);
Serial.println(sessionPresent);
// ESP32 subscribed to esp32/relay topic
uint16_t packetIdSub = mqttClient.subscribe(“esp32/relay”, 0);
Serial.print(“Subscribing at QoS 0, packetId: “);
Serial.println(packetIdSub);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println(“Disconnected from MQTT.”);
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println(“Subscribe acknowledged.”);
Serial.print(” packetId: “);
Serial.println(packetId);
Serial.print(” qos: “);
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println(“Unsubscribe acknowledged.”);
Serial.print(” packetId: “);
Serial.println(packetId);
}
void onMqttPublish(uint16_t packetId) {
Serial.println(“Publish acknowledged.”);
Serial.print(” packetId: “);
Serial.println(packetId);
}
// You can modify this function to handle what happens when you receive a certain message in a specific topic
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
String messageTemp;
for (int i = 0; i < len; i++) {
//Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}
// Check if the MQTT message was received on topic esp32/relay
if (strcmp(topic, “esp32/relay”) == 0) {

if (messageTemp == “1on”) {
// digitalWrite(output25, HIGH);
}
else if (messageTemp == “1off”) {
// digitalWrite(output25, LOW);
}
else if (messageTemp == “2on”) {
// digitalWrite(output26, HIGH);
}
else if (messageTemp == “2off”) {
// digitalWrite(output26, LOW);
}
else if (messageTemp == “3on”) {
// digitalWrite(output27, HIGH);
}
else if (messageTemp == “3off”) {
// digitalWrite(output27, LOW);
}
else if (messageTemp == “4on”) {
// digitalWrite(output33, HIGH);
}
else if (messageTemp == “4off”) {
// digitalWrite(output33, LOW);
}
}

Serial.println(“Publish received.”);
Serial.print(” message: “);
Serial.println(messageTemp);
Serial.print(” topic: “);
Serial.println(topic);
Serial.print(” qos: “);
Serial.println(properties.qos);
Serial.print(” dup: “);
Serial.println(properties.dup);
Serial.print(” retain: “);
Serial.println(properties.retain);
Serial.print(” len: “);
Serial.println(len);
Serial.print(” index: “);
Serial.println(index);
Serial.print(” total: “);
Serial.println(total);
}
void setup() {
// Start the DS18B20 sensor
sensors.begin();

// Define Relay Ouput as an OUTPUT and set it LOW
pinMode(output25, OUTPUT);
digitalWrite(output25, LOW);
pinMode(output26, OUTPUT);
digitalWrite(output26, LOW);
pinMode(output27, OUTPUT);
digitalWrite(output27, LOW);
pinMode(output33, OUTPUT);
digitalWrite(output33, LOW);

Serial.begin(115200);
mqttReconnectTimer = xTimerCreate(“mqttTimer”, pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate(“wifiTimer”, pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
connectToWifi();
}
void loop() {
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 5 seconds)
// it publishes a new MQTT message on topic esp32/temperature
if (currentMillis – previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New temperature readings
sensors.requestTemperatures();
// Publish an MQTT message on topic esp32/temperature with Celsius degrees
uint16_t packetIdPub2 = mqttClient.publish(“esp32/temperature”, 2, true,
String(sensors.getTempCByIndex(0)).c_str());

// Publish an MQTT message on topic esp32/temperature with Fahrenheit degrees
//uint16_t packetIdPub2 = mqttClient.publish(“esp32/temperature”, 2, true,
// String(sensors.getTempFByIndex(0)).c_str());

Serial.print(“Publishing on topic esp32/temperature at QoS 2, packetId: “);
Serial.println(packetIdPub2);
}

}
………………………………………………………………………………………………………………………………………………….

3 Answers
0 Vote Up Vote Down
Steve Mercer answered 4 years ago

The most glaringly obvious thing I see is that you have commented out all of the digitalWrite commands that should turn the pins low or high. For example:

else if (messageTemp == “1off”) {
// digitalWrite(output25, LOW);
}
0 Vote Up Vote Down
Steve Mercer answered 4 years ago

The other thing that jumps out is the different ways you’re comparing strings (Using “==” and “strcmp”). Best practice is to use “==” for single characters and “strcmp” for null terminated strings.

I’m guessing the original code was just comparing to a single number like “1” so “==” was used. When you changed it to “1off” you should have changed the comparison to “strcmp”.

0 Vote Up Vote Down
Mark Bolton answered 4 years ago

Much obliged Steve.   The comments were the big problem. It was switching everything on at initialization and it stayed that way.
I went away and had dinner and a chat with the Missus and then when I sat down refreshed I spotted it instantly  and the symptoms should have given it away.
You are right about the second observation  too. Rui had  the  “0” to set up the test to pick off the esp32/relay topic then had the “on” or  “off” payload doing the toggling.  I was tossing up if I should  have use “oneon, oneoff…. etc for the rest of the else statements.
I will probably tidy that up once I have a clearer idea of the correct combination of commands  / strings / numbers etc…
Thank you kind Sir for you reply
 
Mark

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.