// This example appears to be working with Node Red.
// 2 Way connection via Node Red
// I can control the LED with the switch in Node Red and I get the temperature data from the ESP32.
// https://youtu.be/I52AKly-mSE?si=hhhn-SxADyRnvpy3
// 7:29PM 4/8/2024
// #include <WiFi.h>
// // #include <Adafruit_NeoPixel.h>
// #include <PubSubClient.h>
// // #include <DHTesp.h>
// // https://youtu.be/I52AKly-mSE?si=PDxByik9zV7zUeaC
// const int DHT_PIN = 26;
// DHTesp dht;
// WiFiClient espClient;
// PubSubClient client(espClient);
// const char* ssid = "Wokwi-GUEST"; /// wifi ssid
// const char* password = "";
// const char* mqtt_server = "test.mosquitto.org"; // mosquitto server url
/**************************************************
Home automation code for ESP32 - Arduino IDE
Connect LED + 330 ohm resistor to D2
Connect Potentiometer wiper to D34, 3.3V and gnd
Code for 1st ESP32
*************************************************/
#include <WiFi.h>
#include <PubSubClient.h>
#include <FastLED.h>
#include <DHTesp.h>
#define NUM_LEDS 16
#define DATA_PIN 5
// #define CLOCK_PIN 13
#define BUTTON_PIN 13 // Define the pin connected to the button
#define PIXEL_PIN 5 // Define the pin connected to the NeoPixel LED strip
#define NUM_PIXELS 16 // Define the number of NeoPixels in your strip
// Define the array of leds
CRGB leds[NUM_LEDS];
String macAddressWithoutColon;
// Replace the next variables with your SSID/Password combination
const char* ssid = "Wokwi-GUEST"; /// wifi ssid
const char* password = "";
const char* mqtt_server = "test.mosquitto.org"; // mosquitto server url
WiFiClient espClient;
PubSubClient client(espClient);// To connect more ESP32's change "client" to for instance "client2" here and in the rest of the code
long lastMsg = 0;
char msg[50];
int value = 0;
float temperature = 0;
// int i = 0;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
// const int ledPin = 2; //connect LED to GPIO pin 2
// const int potmeterPin = 34; //Connect Potentiometer to GPIO34
const int buttonPin = 14; // the number of the pushbutton pin
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); // GRB ordering is assumed
// pinMode(ledPin, OUTPUT);//set ledPin to output
pinMode(buttonPin, INPUT);
//Potentiometer GPIO34: no Pinmode for Analog-inputs: The analogRead() function takes care of that :-)
}
void setup_wifi() { // Connect to WiFi network
delay(100);
Serial.println();
Serial.print("Connecting to Wifi");
//Serial.println(ssid); //uncomment if you want to see your SSID in serial monitor
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// if (String(topic) == "esp32/output") {//Check if the MQTT message matches the subscription, if add more ESP32 change topic esp32 to for instance esp33
// Serial.print("Changing output to ");
// if (messageTemp == "true") { //if the message is "true", switch on
// Serial.println("on");
// digitalWrite(ledPin, HIGH);
// }
// else if (messageTemp == "false") { //if the message is "false", switch off
// Serial.println("off");
// digitalWrite(ledPin, LOW);
// }
// } // You can add more "if" statements behind this to control more GPIOs with MQTT
}
void reconnect() {
while (!client.connected()) { // Loop until connected to the MQTT server
Serial.print("Trying MQTT connection...");
if (client.connect("ESP32Client")) { // Try to connect
Serial.println("connected");
client.subscribe("esp32/output"); // Subscribe to topic, if add more ESP32 change topic esp32 to for instance esp33
// This value must match the topic in the switch config of Node Red. (Receiver Side)
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // Wait 5 seconds before retrying
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == LOW) {
leds[0] = CRGB::Red;
FastLED.show();
// client.publish("/button/LOW"); // Publish MQTT topic for button press
client.publish("test", "This is a test message"); //SUBSCRIBE TO TOPIC /temp, pass the value as a string
Serial.println("Button Pressed");
delay(500);
}
}
}
// set the LED:
// digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
/*
[{"id":"10852a22fb5619b2","type":"comment","z":"58b2c5a2fbc5b098","name":"","info":"https://youtu.be/I52AKly-mSE?si=Cex9LIrpkdVznU06\n\n\nMQTT broker authentication\nuser:mqtt-userpass: @eXFs-urb@rB7EgN\n\n\nGui User/pass from Node Red http_node config\nuser: 2d3Wrybzh0\npass: @eXFs-urb@rB7EgN","x":380,"y":240,"wires":[]},{"id":"2e89a2937f12074a","type":"ui_gauge","z":"58b2c5a2fbc5b098","name":"","group":"a3fd5844853ee978","order":2,"width":0,"height":0,"gtype":"gage","title":"gauge","label":"units","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","diff":false,"className":"","x":550,"y":320,"wires":[]},{"id":"47f3f496737e49e2","type":"ui_chart","z":"58b2c5a2fbc5b098","name":"","group":"a3fd5844853ee978","order":3,"width":0,"height":0,"label":"chart","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"className":"","x":550,"y":400,"wires":[[]]},{"id":"bff48737602d1c5d","type":"mqtt out","z":"58b2c5a2fbc5b098","name":"","topic":"esp32/output","qos":"2","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"708f70817de6b58c","x":570,"y":480,"wires":[]},{"id":"37b8ee42e66d0bed","type":"mqtt in","z":"58b2c5a2fbc5b098","name":"","topic":"esp32/temperature","qos":"2","datatype":"auto-detect","broker":"708f70817de6b58c","nl":false,"rap":true,"rh":0,"inputs":0,"x":350,"y":400,"wires":[["2e89a2937f12074a","47f3f496737e49e2","4ba2cd7e3ef143b5"]]},{"id":"5e02713ed3ed8962","type":"ui_switch","z":"58b2c5a2fbc5b098","name":"","label":"switch1","tooltip":"","group":"a3fd5844853ee978","order":1,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"topic","topicType":"msg","style":"","onvalue":"true","onvalueType":"bool","onicon":"","oncolor":"","offvalue":"false","offvalueType":"bool","officon":"","offcolor":"","animate":false,"className":"","x":320,"y":480,"wires":[["bff48737602d1c5d","dedc0b5c879af0a1"]]},{"id":"4ba2cd7e3ef143b5","type":"debug","z":"58b2c5a2fbc5b098","name":"debug 13","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":540,"y":260,"wires":[]},{"id":"dedc0b5c879af0a1","type":"debug","z":"58b2c5a2fbc5b098","name":"debug 14","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":480,"y":580,"wires":[]},{"id":"a3fd5844853ee978","type":"ui_group","name":"ESP32","tab":"38b4d82e7fbd2cf0","order":1,"disp":true,"width":"6","collapse":false,"className":""},{"id":"708f70817de6b58c","type":"mqtt-broker","name":"Mosquitto","broker":"test.mosquitto.org","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"ThinkIOT","birthQos":"0","birthRetain":"false","birthPayload":"output","birthMsg":{},"closeTopic":"","closeQos":"0","closeRetain":"false","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"38b4d82e7fbd2cf0","type":"ui_tab","name":"Default","icon":"dashboard","disabled":false,"hidden":false}]
*/