2024年10月17日 星期四

WOKWI MQTT&Node-Red (Hello & LED)

 WOKWI MQTT&Node-Red  (Hello  & LED)

前篇的延伸 (node-red)

https://alex9ufoexploer.blogspot.com/2024/08/mqtt-basic2-wokwi-esp32-mqtt-box.html




const char broker[] = "test.mosquitto.org";
int        port     = 1883;
const char Pubtopic1[]  = "alex9ufo/hello";
const char Subtopic2[]  = "alex9ufo/led";
meaasge H : 亮 , L : 熄


WOKWI程式

#include <ArduinoMqttClient.h>
#include <WiFi.h>

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] =  "Wokwi-GUEST"; // your network SSID (name)
char pass[] =  "" ;           // your network password (use for WPA, or use as key for WEP)

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "test.mosquitto.org";
int        port     = 1883;
const char Pubtopic1[]  = "alex9ufo/hello";
const char Subtopic2[]  = "alex9ufo/led";
const char willTopic[] = "alex9ufo/Starting";

//set interval for sending messages (milliseconds)

const long interval = 8000;
unsigned long previousMillis = 0;

int count = 0;
const int LED = 2;
char msg[50];
int value = 0;

//=======================================================================
void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");
  String Topic= mqttClient.messageTopic();

  String message="";
  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    //Serial.print((char)mqttClient.read());
    message += (char)mqttClient.read();
  }
  Serial.println(message);
  message.trim();
  Topic.trim();

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

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

//=======================================================================
//副程式  setup wifi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);     //print ssid
  WiFi.begin(ssid, pass);  //初始化WiFi 函式庫並回傳目前的網路狀態
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }   //假設 wifi 未連接 show ………

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}  

//=======================================================================
void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(115200);
  pinMode(LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output

  Serial.begin(115200);   // Initialize serial communications with the PC
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
 
  setup_wifi();
  Serial.println("You're connected to the network");
  Serial.println();
 
  String willPayload = "ESP32 Start working....!";
  bool willRetain = true;
  int willQos = 1;

  mqttClient.beginWill(willTopic, willPayload.length(), willRetain, willQos);
  mqttClient.print(willPayload);
  mqttClient.endWill();

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);
  Serial.print("Subscribing to topic: ");
  Serial.println(Subtopic2);
  // subscribe to a topic
  // the second parameter sets the QoS of the subscription,
  // the the library supports subscribing at QoS 0, 1, or 2
  int subscribeQos = 1;
  mqttClient.subscribe(Subtopic2, subscribeQos);

}

//=======================================================================
void loop() {
  // call poll() regularly to allow the library to send MQTT keep alive which
  // avoids being disconnected by the broker
  mqttClient.poll();

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    //record random value from A0, A1 and A2
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);

    Serial.print("Sending message to topic: ");
    Serial.println(Pubtopic1);
    Serial.println(msg);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(Pubtopic1);
    mqttClient.print(msg);
    mqttClient.endMessage();

    Serial.println();
  }
}

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年10月2日 星期三

WOKWI MQTT (DHT22 & 16*2 LCD & LED)

 WOKWI  MQTT (DHT22 & 16*2 LCD & LED)

const char* mqtt_server = "broker.mqttgo.io";
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());
  }
}

WOKWI MQTT&Node-Red (Hello & LED)

 WOKWI MQTT&Node-Red  (Hello  & LED) 前篇的延伸 (node-red) https://alex9ufoexploer.blogspot.com/2024/08/mqtt-basic2-wokwi-esp32-mqtt-box....