2024年6月4日 星期二

WOKWI ESP32 connects to the free public MQTT broker (3)

WOKWI ESP32 connects to the free public MQTT broker (3)  ---Node-Red




WOKWI程式


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

//#define LED 13      //定義LED接腳
int LED = 13;

char ssid[]="Wokwi-GUEST";
char pass[]="";

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

//const char broker[] = "test.mosquitto.org";
const char broker[] = "broker.emqx.io";
int        port     = 1883;

const char *SubTopic1 = "alex9ufo/LED_control";
const char *PubTopic1 = "alex9ufo/Hi";

const char willTopic[] = "alex9ufo/Starting";

//布林代數 LED狀態 是否連上網路ESP32 ready ?
bool ledState = false;
bool atwork = false;
String LEDjson = "";
bool Flash = false;  //true

String json = "";
unsigned long previousMillis = 0;
unsigned long interval = 10000;

unsigned long Cnt=0;
//===========================================================
void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.print("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  String Topic= mqttClient.messageTopic();
  Serial.print("', duplicate = ");
  Serial.print(mqttClient.messageDup() ? "true" : "false");
  Serial.print(", QoS = ");
  Serial.print(mqttClient.messageQoS());
  Serial.print(", retained = ");
  Serial.print(mqttClient.messageRetain() ? "true" : "false");
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");
  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_control") {
  if (message == "on") {
    digitalWrite(LED, LOW);  // Turn on the LED
    //ledState = true;  //ledState = ture HIGH
    //設定 各個 旗號
    LEDjson ="ON";
    Flash = false;
    Serial.print("LED =");
    Serial.println(LEDjson);
  }

  if (message == "off" ) {
    digitalWrite(LED, HIGH); // Turn off the LED
    //ledState = false; //ledState = false LOW
    LEDjson ="OFF";
    Flash = false;
    Serial.print("LED =");
    Serial.println(LEDjson);
  }
 
  if (message == "flash" ) {
    digitalWrite(LED, HIGH); // Turn off the LED
    Flash = true;
    LEDjson ="FLASH";
    Serial.print("LED =");
    Serial.println(LEDjson);      
  }

    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());
}  
//===========================================================
//判斷 旗號Flash , Timer 是否為真
void LED_Message() {
  //判斷 旗號 Flash / timer  是否為真 ? 閃爍 定時
 
  if (Flash){
    digitalWrite(LED, !digitalRead(LED));
    delay(500);
    if (digitalRead(LED))
      ledState = true;
    else
      ledState = false;

  } //(Flash)
}
//===========================================================
void setup() {
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);  // Turn off the LED initially
  //Initialize serial and wait for port to open:
  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(SubTopic1);
 
  // 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(SubTopic1, subscribeQos);

  Serial.println();
  delay(4);       // Optional delay. Some board do need more time after init to be ready, see Readme
}

//===========================================================
void loop() {
  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();
  LED_Message();
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >=interval) {

    bool retained = false;
    int qos = 1;
    bool dup = false;
    Cnt=Cnt+1;
   
    json="Hi EMQX I'm ESP32 ^^ " + String(Cnt);
    mqttClient.beginMessage(PubTopic1,  json.length(), retained, qos, dup);
    mqttClient.print(json);
    mqttClient.endMessage();
    Serial.println(json);
    previousMillis = currentMillis;
 }
}
////===========================================================

Node-Red程式



[{"id":"c01c12376d33be80","type":"ui_button","z":"eb00260d98e4aedd","name":"","group":"eb0aed8fdb14c323","order":1,"width":2,"height":1,"passthru":false,"label":"ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"on","payloadType":"str","topic":"topic","topicType":"msg","x":150,"y":40,"wires":[["3c149c179f9f785c","385239026ca34417","0ee1b68bf923e0a4"]]},{"id":"00c8340b0da8a4da","type":"ui_button","z":"eb00260d98e4aedd","name":"","group":"eb0aed8fdb14c323","order":2,"width":2,"height":1,"passthru":false,"label":"OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"off","payloadType":"str","topic":"topic","topicType":"msg","x":150,"y":100,"wires":[["3c149c179f9f785c","385239026ca34417","0ee1b68bf923e0a4"]]},{"id":"ab753975e933c4ac","type":"ui_button","z":"eb00260d98e4aedd","name":"","group":"eb0aed8fdb14c323","order":3,"width":2,"height":1,"passthru":false,"label":"FLASH","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"flash","payloadType":"str","topic":"topic","topicType":"msg","x":160,"y":160,"wires":[["3c149c179f9f785c","385239026ca34417","0ee1b68bf923e0a4"]]},{"id":"3c149c179f9f785c","type":"ui_audio","z":"eb00260d98e4aedd","name":"","group":"eb0aed8fdb14c323","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":385,"y":100,"wires":[],"l":false},{"id":"82f93052f1c64a56","type":"ui_toast","z":"eb00260d98e4aedd","position":"top right","displayTime":"3","highlight":"","sendall":true,"outputs":0,"ok":"OK","cancel":"Cancel","raw":true,"className":"","topic":"","name":"","x":440,"y":280,"wires":[]},{"id":"385239026ca34417","type":"mqtt out","z":"eb00260d98e4aedd","name":"Control LED  ","topic":"alex9ufo/LED_control","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"dce5aa632b12c4cc","x":430,"y":40,"wires":[]},{"id":"0ee1b68bf923e0a4","type":"debug","z":"eb00260d98e4aedd","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":410,"y":160,"wires":[]},{"id":"f6eb009262e14a35","type":"ui_text","z":"eb00260d98e4aedd","group":"eb0aed8fdb14c323","order":5,"width":6,"height":2,"name":"","label":"MQTT來的","format":"<font color = RED>{{msg.payload}}","layout":"row-left","className":"","x":430,"y":240,"wires":[]},{"id":"00da086c2edfdfd8","type":"mqtt in","z":"eb00260d98e4aedd","name":"Hi","topic":"alex9ufo/Hi","qos":"1","datatype":"auto-detect","broker":"dce5aa632b12c4cc","nl":false,"rap":true,"rh":0,"inputs":0,"x":150,"y":240,"wires":[["f6eb009262e14a35","82f93052f1c64a56"]]},{"id":"eb0aed8fdb14c323","type":"ui_group","name":"MQTT Basic 3","tab":"2eed7cc3b24b8f69","order":4,"disp":true,"width":"6","collapse":false,"className":""},{"id":"dce5aa632b12c4cc","type":"mqtt-broker","name":"EMQx","broker":"broker.emqx.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"5","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"2eed7cc3b24b8f69","type":"ui_tab","name":"WOKWI_LED","icon":"dashboard","order":125,"disabled":false,"hidden":false}]


https://www.youtube.com/watch?v=kvcS2kDAFzw

https://www.youtube.com/watch?v=R-zcDJcoG1o





沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...