Friday, November 10, 2023

ESP 32 4 / 8 Relay MQTT Module.

UPDATE : 
 
I dont like the protoboard / bird's nest approach. 
 
There are 8 channel relay boards with ESP 32 available at very afffordable prices. Much nicer way to go.   30 bucks and wouldnt have to buggerise around with connectors... Just use those staright pins crimps in the screw block ... all round winner.
 
 
-------------------------------------------------------------------------------------------------------
 
Have just built an 8 channel version of the hardware. Time to revisit the sketch and modify it for the new board. Even better make a sketch that will work on both. 

 Ref : https://randomnerdtutorials.com/esp32-relay-module-ac-web-server/

 Hacked the sketch to give three extra channels and set up a Node Red Interface ... 



/*********
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 <Arduino.h>

#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;
// 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, LOW);
}
else if (messageTemp == "1off") {
digitalWrite(output25, HIGH);
}
else if (messageTemp == "2on") {
digitalWrite(output26, LOW);
}
else if (messageTemp == "2off") {
digitalWrite(output26, HIGH);
}
else if (messageTemp == "3on") {
digitalWrite(output27, LOW);
}
else if (messageTemp == "3off") {
digitalWrite(output27, HIGH);
}
else if (messageTemp == "4on") {
digitalWrite(output33, LOW);
}
else if (messageTemp == "4off") {
digitalWrite(output33, HIGH);
}
}
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);

}
}

 

No comments:

Post a Comment