2025_1 Node-red & DHT22 4LED Control
wokwi ESP32 Arduino程式
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
//Relays for switching appliances
#define Relay1 15 //D15 LED-Orangs = Water-1
#define Relay2 2 //D2 LED-Blue = Water-2
#define Relay3 19 //D19 LED-Blue = Motor
#define Relay4 23 //D23 LED-RED = Fan
//Nenu For Control
int menu;
//Changs to:
#define sub1 "alex9ufo/2025/RELAY"
#define pub1 "alex9ufo/2025/DHT22"
//DHT11 for reading temperature and humidity value
#define DHTPIN 13 //D13 DHTPIN
// Uncomment whatever type you're using!
#define DHTTYPE DHT22 // DHT 22
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org"; // Local IP address of Raspberry Pi
const char* username = "";
const char* pass = "";
char str_hum_data[10];
char str_temp_data[10];
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
//===============================================
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//==============================================================
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String message="";
for (int i = 0; i < length; i++) {
message += (char) payload[i]; // Convert *byte to string
}
Serial.print(message);
if (strstr(topic, sub1)) //Button 1
{
if (message == "1on" ) {
digitalWrite(Relay1, HIGH); // Turn on the LED
}
if (message == "1off" ) {
digitalWrite(Relay1, LOW); // Turn off the LED
}
if (message == "2on" ) {
digitalWrite(Relay2, HIGH); // Turn on the LED
}
if (message == "2off" ) {
digitalWrite(Relay2, LOW); // Turn off the LED
}
if (message == "3on" ) {
digitalWrite(Relay3, HIGH); // Turn on the LED
}
if (message == "3off" ) {
digitalWrite(Relay3, LOW); // Turn off the LED
}
if (message == "4on" ) {
digitalWrite(Relay4, HIGH); // Turn on the LED
}
if (message == "4off" ) {
digitalWrite(Relay4, LOW); // Turn off the LED
}
}
else{
Serial.println("unsubscribed topic");
}
}
//==============================================================
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), username, pass) ) {
Serial.println("connected");
client.subscribe(sub1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//==============================================================
void setup() {
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
client.subscribe(pub1);
}
//==============================================================
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 5000) {
float hum_data = dht.readHumidity();
Serial.println(hum_data);
/* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
dtostrf(hum_data, 4, 1, str_hum_data);
float temp_data = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit
dtostrf(temp_data, 4, 1, str_temp_data);
lastMsg = now;
Serial.println("Publish message: ");
Serial.print("Temperature: "); Serial.println(str_temp_data);
//client.publish("device2/temp", str_temp_data);
Serial.print("Humidity: "); Serial.println(str_hum_data);
//client.publish("device2/hum", str_hum_data);
String pubStr ,pubStr1 ,pubStr2;
pubStr1=String(str_temp_data);
pubStr2=String(str_hum_data);
pubStr=pubStr1 + "," + pubStr2;
// Length (with one extra character for the null terminator)
int pubStr_len = pubStr.length() + 1;
// Prepare the character array (the buffer)
char char_array[pubStr_len];
// Copy it over
pubStr.toCharArray(char_array, pubStr_len);
client.publish(pub1, char_array);
}
}
Node-Red程式
[{"id":"0e3d6695a6879524","type":"tab","label":"流程2","disabled":false,"info":"","env":[]},{"id":"cb8d51907b20704f","type":"mqtt out","z":"0e3d6695a6879524","name":"RELAY Publish","topic":"alex9ufo/2025/RELAY","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"21957383cfd8785a","x":360,"y":180,"wires":[]},{"id":"ef638dcdba5e028d","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":1,"width":3,"height":1,"passthru":false,"label":"1:ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"1on","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":40,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"c32bc2fe5ac82daa","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":2,"width":3,"height":1,"passthru":false,"label":"1:OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"1off","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":80,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"b70988573b2c8f5e","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":3,"width":3,"height":1,"passthru":false,"label":"2:ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"2on","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":140,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"9edd136cd324e2e7","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":4,"width":3,"height":1,"passthru":false,"label":"2:OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"2off","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":180,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"c05aecb01e77bafa","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":5,"width":3,"height":1,"passthru":false,"label":"3:ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"3on","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":240,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"4a7b48586a2ffd40","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":6,"width":3,"height":1,"passthru":false,"label":"3:OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"3off","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":280,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"8880d1e1a38da608","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":7,"width":3,"height":1,"passthru":false,"label":"4:ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"4on","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":340,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"d846746510e04ca1","type":"ui_button","z":"0e3d6695a6879524","name":"","group":"0779966bd8e8a054","order":8,"width":3,"height":1,"passthru":false,"label":"4:OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"4off","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":380,"wires":[["cb8d51907b20704f","05dc03dbc6a93c7e"]]},{"id":"05dc03dbc6a93c7e","type":"debug","z":"0e3d6695a6879524","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":330,"y":260,"wires":[]},{"id":"daa0e3861c44ec65","type":"mqtt in","z":"0e3d6695a6879524","name":"DHT22 Subscribe","topic":"alex9ufo/2025/DHT22","qos":"1","datatype":"auto-detect","broker":"21957383cfd8785a","nl":false,"rap":true,"rh":0,"inputs":0,"x":450,"y":100,"wires":[["c8955107b425eca4","960a244f76063625"]]},{"id":"c8955107b425eca4","type":"debug","z":"0e3d6695a6879524","name":"debug 237","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":670,"y":80,"wires":[]},{"id":"c35b8257d4d8d6b5","type":"ui_gauge","z":"0e3d6695a6879524","name":"","group":"d0cbade7d80c5d17","order":1,"width":3,"height":3,"gtype":"gage","title":"溫度","label":"°C","format":"{{value}}","min":"-40","max":"80","colors":["#00b500","#e6e600","#ca3838"],"seg1":"20","seg2":"40","className":"","x":890,"y":140,"wires":[]},{"id":"d0bab0dfeedc004f","type":"ui_gauge","z":"0e3d6695a6879524","name":"","group":"d0cbade7d80c5d17","order":2,"width":3,"height":3,"gtype":"gage","title":"濕度","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"40","seg2":"60","className":"","x":890,"y":260,"wires":[]},{"id":"960a244f76063625","type":"function","z":"0e3d6695a6879524","name":"分離","func":"msg.payload = msg.payload.split(\",\");\nreturn msg;\n","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"","libs":[],"x":550,"y":200,"wires":[["a409403ae64c211d","92ee6ff3b0350638"]]},{"id":"a409403ae64c211d","type":"function","z":"0e3d6695a6879524","name":"get 溫度","func":"msg.payload=msg.payload[0];\nreturn msg;","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"","libs":[],"x":700,"y":140,"wires":[["b13259fc83495aaa","c35b8257d4d8d6b5"]]},{"id":"92ee6ff3b0350638","type":"function","z":"0e3d6695a6879524","name":"get 濕度","func":"msg.payload=msg.payload[1];\nreturn msg;","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"","libs":[],"x":700,"y":240,"wires":[["9f2704443b5c9370","d0bab0dfeedc004f"]]},{"id":"b13259fc83495aaa","type":"debug","z":"0e3d6695a6879524","name":"debug 330","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":910,"y":180,"wires":[]},{"id":"9f2704443b5c9370","type":"debug","z":"0e3d6695a6879524","name":"debug 331","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":910,"y":220,"wires":[]},{"id":"21957383cfd8785a","type":"mqtt-broker","name":"test.mosquitto.org","broker":"test.mosquitto.org","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closeRetain":"false","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"0779966bd8e8a054","type":"ui_group","name":"RELAY","tab":"0a96b8dde1b2e50a","order":1,"disp":true,"width":"6","collapse":false,"className":""},{"id":"d0cbade7d80c5d17","type":"ui_group","name":"DHT22","tab":"0a96b8dde1b2e50a","order":2,"disp":true,"width":"6","collapse":false,"className":""},{"id":"0a96b8dde1b2e50a","type":"ui_tab","name":"DHT22&RELAY","icon":"dashboard","order":2,"disabled":false,"hidden":false}]
沒有留言:
張貼留言