2024年10月3日 星期四

WOKWI MQTT&Node-Red (DHT22 & 16*2 LCD & LED)

WOKWI MQTT&Node-Red  (DHT22 & 16*2 LCD & LED)

前一篇的延伸

https://alex9ufoexploer.blogspot.com/2024/10/wokwi-mqtt-dht22-162-lcd-led.html






MQTT相關資料

const char* mqtt_server = "broker.mqttgo.io";
//const char* mqtt_server = "test.mosquitto.org";

const char Pubtopic1[]  = "alex9ufo/temp";
const char Pubtopic2[]  = "alex9ufo/hum";
const char Subtopic1[]  = "alex9ufo/command";



WOKWI程式


#include <WiFi.h>
#include <PubSubClient.h>
#include <LiquidCrystal_I2C.h>
#include "DHTesp.h"

const int DHT_PIN = 15;
const int LED = 2;

DHTesp dhtSensor;

#define I2C_ADDR    0x27
#define LCD_COLUMNS 20
#define LCD_LINES   4

LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);

// Update these with values suitable for your network.
const char* ssid =  "Wokwi-GUEST";   // your network SSID (name)
const char* password = "";   // your network password
//const char* mqtt_server = "broker.mqttdashboard.com";// choose your mqtt server
const char* mqtt_server = "broker.mqttgo.io";
//const char* mqtt_server = "test.mosquitto.org";

const char Pubtopic1[]  = "alex9ufo/temp";
const char Pubtopic2[]  = "alex9ufo/hum";
const char Subtopic1[]  = "alex9ufo/command";

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
int value = 0;

//=========================================================
void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Command from MQTT broker is : [");
  Serial.print(topic);
  Serial.print("]");
  Serial.println();
  Serial.print(" publish data is:");
  lcd.clear();
  String message="";
  {
    for(int i=0;i<length;i++)
    {
      Serial.print((char)payload[i]);  
      message +=(char)payload[i];

      lcd.setCursor(0, 0);
      lcd.print("alex9ufo LCD"); // Start Print text to Line 1
      lcd.setCursor(i, 1);
      lcd.write((char)payload[i]);
    }
  }
 
  //Serial.println(message);
  message.trim();

  if (message == "on") {
      digitalWrite(LED, LOW);  // Turn on the LED
      Serial.print("LED = on ");
  }

  if (message == "off" ) {
      digitalWrite(LED, HIGH); // Turn off the LED
      Serial.print("LED = off ");
  }

  Serial.println();
} //end callback
//=========================================================
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 you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
      //once connected to MQTT broker, subscribe command if any
      //client.subscribe("alex9ufo/Command");
      client.subscribe(Subtopic1);

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()
//=========================================================
void setup_wifi() {
   delay(100);
  // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    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 setup() {
  Serial.begin(115200);
 
  pinMode(LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
 
  // Init
  lcd.init();
  lcd.backlight();

  // Print something
  lcd.setCursor(3, 0);
  lcd.print("Welcome to");
  lcd.setCursor(2, 1);
  lcd.print("lcd display");
  lcd.setCursor(5, 2);
  lcd.print("Simulator");
  lcd.setCursor(7, 3);
  lcd.print("Enjoy!");
}


void loop() {
    if (!client.connected()) {
    reconnect();
  }
  client.setCallback(callback);
  client.loop();
  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("alex9ufo/temp", temp.c_str());
   
    String hum = String(data.humidity, 1);
    Serial.print("Humidity: ");
    Serial.println(hum);
    client.publish("alex9ufo/hum", hum.c_str());
  }
}


Node-Red程式

[{"id":"583f0b243b76dcfb","type":"debug","z":"663d84419464c1bb","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":350,"y":160,"wires":[]},{"id":"dfca4f0bac560241","type":"mqtt in","z":"663d84419464c1bb","name":"temperature","topic":"alex9ufo/temp","qos":"0","datatype":"auto-detect","broker":"584db2f88f8050c2","nl":false,"rap":true,"rh":0,"inputs":0,"x":190,"y":160,"wires":[["583f0b243b76dcfb","6111ea979ef12f69"]]},{"id":"0a38ae48ebd01c2c","type":"mqtt in","z":"663d84419464c1bb","name":"humidity","topic":"alex9ufo/hum","qos":"0","datatype":"auto-detect","broker":"450dc18180d64bb4","nl":false,"rap":true,"rh":0,"inputs":0,"x":180,"y":260,"wires":[["7e40988d269b5f4f","218248ed02fedb0d"]]},{"id":"7e40988d269b5f4f","type":"debug","z":"663d84419464c1bb","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":350,"y":260,"wires":[]},{"id":"218248ed02fedb0d","type":"ui_chart","z":"663d84419464c1bb","name":"","group":"2068daa4fbffb834","order":1,"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":350,"y":300,"wires":[[]]},{"id":"6111ea979ef12f69","type":"ui_gauge","z":"663d84419464c1bb","name":"","group":"f64e1fe3358c5078","order":1,"width":0,"height":0,"gtype":"gage","title":"gauge","label":"°C","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"20","seg2":"50","className":"","x":350,"y":220,"wires":[]},{"id":"f74212f0fa165a21","type":"ui_button","z":"663d84419464c1bb","name":"","group":"162a5ed3f7b99560","order":1,"width":0,"height":0,"passthru":false,"label":"ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"on","payloadType":"str","topic":"topic","topicType":"msg","x":170,"y":340,"wires":[["52d60600147bb655"]]},{"id":"19da8774110add6a","type":"ui_button","z":"663d84419464c1bb","name":"","group":"162a5ed3f7b99560","order":2,"width":0,"height":0,"passthru":false,"label":"OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"off","payloadType":"str","topic":"topic","topicType":"msg","x":170,"y":400,"wires":[["52d60600147bb655"]]},{"id":"52d60600147bb655","type":"mqtt out","z":"663d84419464c1bb","name":"LED_control","topic":"alex9ufo/command","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"66ed58be41f6b311","x":370,"y":380,"wires":[]},{"id":"584db2f88f8050c2","type":"mqtt-broker","name":"broker.mqttgo.io","broker":"broker.mqttgo.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":"","credentials":{}},{"id":"450dc18180d64bb4","type":"mqtt-broker","name":"broker.mqttgo.io","broker":"broker.mqttgo.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"2068daa4fbffb834","type":"ui_group","name":"humidity","tab":"f304c5db6c1258cc","order":2,"disp":true,"width":"6","collapse":false,"className":""},{"id":"f64e1fe3358c5078","type":"ui_group","name":"temperature","tab":"f304c5db6c1258cc","order":1,"disp":true,"width":"6","collapse":false,"className":""},{"id":"162a5ed3f7b99560","type":"ui_group","name":"LED_control","tab":"f304c5db6c1258cc","order":3,"disp":true,"width":"6","collapse":false,"className":""},{"id":"66ed58be41f6b311","type":"mqtt-broker","name":"broker.mqttgo.io","broker":"broker.mqttgo.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"f304c5db6c1258cc","type":"ui_tab","name":"WOKWI_DHT22","icon":"dashboard","order":127,"disabled":false,"hidden":false}]

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...