WOKWI DHT22 & LED (Node-Red)
WOKWI程式
Node-Red程式
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const int LED_PIN = 12;
DHTesp dhtSensor;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";
const char *SubTopic1 = "ale9ufo/mqtt/led";
const char *PubTopic1 = "ale9ufo/mqtt/temp";
const char *PubTopic2 = "ale9ufo/mqtt/hum";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
float temp = 0;
float hum = 0;
int value = 0;
String LEDjson = "";
bool Flash = false; //true
//=========================================================================
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 messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}
if (strcmp(topic, SubTopic1) == 0) {
// If the relay is on turn it off (and vice-versa)
Serial.println();
Serial.println(messageTemp);
if (messageTemp == "on") {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
//ledState = true; //ledState = ture HIGH
//設定 各個 旗號
LEDjson ="ON";
Flash = false;
Serial.print("LED =");
Serial.println(LEDjson);
}
if (messageTemp == "off" ) {
digitalWrite(LED_PIN , LOW); // Turn off the LED
//ledState = false; //ledState = false LOW
LEDjson ="OFF";
Flash = false;
Serial.print("LED =");
Serial.println(LEDjson);
}
if (messageTemp == "flash" ) {
digitalWrite(LED_PIN, HIGH); // Turn off the LED
Flash = true;
LEDjson ="FLASH";
Serial.print("LED =");
Serial.println(LEDjson);
}
}
}
//=========================================================================
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("Connected");
// Once connected, publish an announcement...
client.publish("ale9ufo/mqtt", "Indobot");
// ... and resubscribe
client.subscribe(SubTopic1);
} 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(LED_PIN, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
client.subscribe(SubTopic1);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}
//=========================================================================
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if (Flash){
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
delay(250);
} //(Flash)
unsigned long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String temp = String(data.temperature, 2);
Serial.print("Temperature: ");
Serial.println(temp);
client.publish(PubTopic1, temp.c_str());
String hum = String(data.humidity, 1);
Serial.print("Humidity: ");
Serial.println(hum);
client.publish(PubTopic2, hum.c_str());
}
}
//=========================================================================
[
{
"id": "ba42d4b5dbf8aef2",
"type": "ui_led",
"z": "551bcfad002a399e",
"order": 4,
"group": "025f9ffb9a6ef09a",
"width": 6,
"height": 3,
"label": "",
"labelPlacement": "left",
"labelAlignment": "left",
"colorForValue": [
{
"color": "#ff0000",
"value": "false",
"valueType": "bool"
},
{
"color": "#008000",
"value": "true",
"valueType": "bool"
}
],
"allowColorForValueInMessage": false,
"shape": "circle",
"showGlow": true,
"name": "",
"x": 530,
"y": 740,
"wires": []
},
{
"id": "19dba15641b16f18",
"type": "ui_button",
"z": "551bcfad002a399e",
"name": "",
"group": "025f9ffb9a6ef09a",
"order": 1,
"width": 2,
"height": 1,
"passthru": false,
"label": "ON",
"tooltip": "",
"color": "",
"bgcolor": "",
"className": "",
"icon": "",
"payload": "on",
"payloadType": "str",
"topic": "topic",
"topicType": "msg",
"x": 70,
"y": 620,
"wires": [
[
"364f12c3e131bf5a",
"cc1b11b1.bebb28"
]
]
},
{
"id": "10c57c6d4f586617",
"type": "ui_button",
"z": "551bcfad002a399e",
"name": "",
"group": "025f9ffb9a6ef09a",
"order": 2,
"width": 2,
"height": 1,
"passthru": false,
"label": "OFF",
"tooltip": "",
"color": "",
"bgcolor": "",
"className": "",
"icon": "",
"payload": "off",
"payloadType": "str",
"topic": "topic",
"topicType": "msg",
"x": 70,
"y": 680,
"wires": [
[
"364f12c3e131bf5a",
"cc1b11b1.bebb28"
]
]
},
{
"id": "84e38b3103221443",
"type": "ui_button",
"z": "551bcfad002a399e",
"name": "",
"group": "025f9ffb9a6ef09a",
"order": 3,
"width": 2,
"height": 1,
"passthru": false,
"label": "FLASH",
"tooltip": "",
"color": "",
"bgcolor": "",
"className": "",
"icon": "",
"payload": "flash",
"payloadType": "str",
"topic": "topic",
"topicType": "msg",
"x": 80,
"y": 740,
"wires": [
[
"364f12c3e131bf5a",
"740a99d2.b07d1"
]
]
},
{
"id": "b1438827a15daca1",
"type": "mqtt in",
"z": "551bcfad002a399e",
"name": "溫度",
"topic": "ale9ufo/mqtt/temp",
"qos": "1",
"datatype": "auto-detect",
"broker": "21957383cfd8785a",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 70,
"y": 820,
"wires": [
[
"556542bd764c1eff"
]
]
},
{
"id": "364f12c3e131bf5a",
"type": "mqtt out",
"z": "551bcfad002a399e",
"name": "LED",
"topic": "ale9ufo/mqtt/led",
"qos": "1",
"retain": "true",
"respTopic": "",
"contentType": "",
"userProps": "",
"correl": "",
"expiry": "",
"broker": "21957383cfd8785a",
"x": 250,
"y": 580,
"wires": []
},
{
"id": "f6e68b33575b33b2",
"type": "function",
"z": "551bcfad002a399e",
"name": "function true/false",
"func": "var tmp=msg.payload;\nif (tmp=='on')\n msg.payload=true;\nif (tmp=='off')\n msg.payload=false; \nif (tmp==1)\n msg.payload=true;\nif (tmp==0)\n msg.payload=false; \nreturn msg;",
"outputs": 1,
"timeout": 0,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 430,
"y": 700,
"wires": [
[
"ba42d4b5dbf8aef2",
"941738b4b00a05de"
]
]
},
{
"id": "556542bd764c1eff",
"type": "ui_gauge",
"z": "551bcfad002a399e",
"name": "",
"group": "b2a47d9211a4d9b9",
"order": 1,
"width": 4,
"height": 3,
"gtype": "gage",
"title": "溫度",
"label": "℃",
"format": "{{value}}",
"min": "-40",
"max": "80",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "30",
"seg2": "45",
"className": "",
"x": 210,
"y": 820,
"wires": []
},
{
"id": "75b4ccfded4ff808",
"type": "mqtt in",
"z": "551bcfad002a399e",
"name": "濕度",
"topic": "ale9ufo/mqtt/hum",
"qos": "1",
"datatype": "auto-detect",
"broker": "21957383cfd8785a",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 330,
"y": 820,
"wires": [
[
"711c2594688a61a9"
]
]
},
{
"id": "711c2594688a61a9",
"type": "ui_gauge",
"z": "551bcfad002a399e",
"name": "",
"group": "b2a47d9211a4d9b9",
"order": 5,
"width": 4,
"height": 3,
"gtype": "gage",
"title": "濕度",
"label": "%RH",
"format": "{{value}}",
"min": "5",
"max": "90",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "50",
"seg2": "65",
"className": "",
"x": 470,
"y": 820,
"wires": []
},
{
"id": "941738b4b00a05de",
"type": "debug",
"z": "551bcfad002a399e",
"name": "debug ",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 530,
"y": 620,
"wires": []
},
{
"id": "740a99d2.b07d1",
"type": "function",
"z": "551bcfad002a399e",
"name": "startBlink",
"func": "var BLINKDELAY = 250;\nvar light = true;\nvar blinker = setInterval(blink, BLINKDELAY);\nglobal.set(\"blinker\", blinker);\nfunction blink () {\n \n if (light) {\n msg.payload = 1;\n light = false;\n }\n \n else {\n msg.payload = 0;\n light = true;\n }\n \n node.send(msg);\n}\nreturn;",
"outputs": 1,
"timeout": "",
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 240,
"y": 740,
"wires": [
[
"f6e68b33575b33b2",
"32141e3321b5cef2"
]
]
},
{
"id": "cc1b11b1.bebb28",
"type": "function",
"z": "551bcfad002a399e",
"name": "stopBlink",
"func": "clearInterval(global.get(\"blinker\"));\nreturn msg;",
"outputs": 1,
"timeout": "",
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 240,
"y": 680,
"wires": [
[
"f6e68b33575b33b2",
"93585ef08ce182fa"
]
]
},
{
"id": "93585ef08ce182fa",
"type": "debug",
"z": "551bcfad002a399e",
"name": "debug ",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 370,
"y": 640,
"wires": []
},
{
"id": "32141e3321b5cef2",
"type": "debug",
"z": "551bcfad002a399e",
"name": "debug ",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 370,
"y": 760,
"wires": []
},
{
"id": "025f9ffb9a6ef09a",
"type": "ui_group",
"name": "LED",
"tab": "6b8b15295653aa3c",
"order": 2,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"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": "b2a47d9211a4d9b9",
"type": "ui_group",
"name": "DHT22",
"tab": "6b8b15295653aa3c",
"order": 2,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "6b8b15295653aa3c",
"type": "ui_tab",
"name": "ESP32",
"icon": "dashboard",
"order": 7,
"disabled": false,
"hidden": false
}
]
沒有留言:
張貼留言