2023年8月26日 星期六

實驗1-2 2023-08 ESP32 + RFID + MQTT Explorer + Google App MyMQTT + Node-Red

 實驗1-2 2023-08  ESP32 + RFID + MQTT Explorer + Google App MyMQTT + Node-Red






// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";
const char *topic1 = "alex9ufo/esp32/led";
const char *topic2 = "alex9ufo/esp32/RFID";


































  或







[{"id":"580c94b9d2d28477","type":"ui_button","z":"e4cba267a9614782","name":"","group":"d783cb980c3979fc","order":16,"width":2,"height":1,"passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":140,"y":100,"wires":[["e04b9ae6c9cf13a0","1ddef96e0b39a7ed","5763812d921d3686"]]},{"id":"8d12b5b63d88d34d","type":"ui_button","z":"e4cba267a9614782","name":"","group":"d783cb980c3979fc","order":18,"width":2,"height":1,"passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"off","payloadType":"str","topic":"","topicType":"str","x":140,"y":140,"wires":[["e04b9ae6c9cf13a0","1ddef96e0b39a7ed","5763812d921d3686"]]},{"id":"e04b9ae6c9cf13a0","type":"mqtt out","z":"e4cba267a9614782","name":"Control LED","topic":"alex9ufo/esp32/led","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":390,"y":100,"wires":[]},{"id":"17fde028714c2ffe","type":"comment","z":"e4cba267a9614782","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":270,"y":40,"wires":[]},{"id":"1ddef96e0b39a7ed","type":"ui_audio","z":"e4cba267a9614782","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":380,"y":180,"wires":[]},{"id":"5763812d921d3686","type":"ui_text","z":"e4cba267a9614782","group":"d783cb980c3979fc","order":20,"width":10,"height":2,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":140,"wires":[]},{"id":"1eaabded303264f6","type":"ui_audio","z":"e4cba267a9614782","name":"","group":"d783cb980c3979fc","voice":"Google US English","always":"","x":380,"y":340,"wires":[]},{"id":"a205cc8ff1b96783","type":"mqtt in","z":"e4cba267a9614782","name":"RFID Card","topic":"alex9ufo/esp32/RFID","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":160,"y":400,"wires":[["1eaabded303264f6","49d0a9e2f1d09530","c702f883eaed76eb"]]},{"id":"49d0a9e2f1d09530","type":"debug","z":"e4cba267a9614782","name":"debug 94","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":380,"y":420,"wires":[]},{"id":"a04b2d423bfd191b","type":"comment","z":"e4cba267a9614782","name":"Node-Red  subscribe HiveMQ Broker  , ESP32發行","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":260,"y":280,"wires":[]},{"id":"c702f883eaed76eb","type":"ui_text","z":"e4cba267a9614782","group":"d783cb980c3979fc","order":21,"width":10,"height":2,"name":"","label":"Node-RED 訂閱MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":440,"y":380,"wires":[]},{"id":"d783cb980c3979fc","type":"ui_group","name":"Demo","tab":"0449b3b1fea99d52","order":1,"disp":true,"width":"10","collapse":false,"className":""},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":4,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"2023 Storing IOT Data ","tab":"6249073d2714bfd4","order":1,"disp":true,"width":"16","collapse":true,"className":""},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"compatmode":false,"protocolVersion":4,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"0449b3b1fea99d52","type":"ui_tab","name":"Demo","icon":"dashboard","disabled":false,"hidden":false},{"id":"6249073d2714bfd4","type":"ui_tab","name":"RFID Home","icon":"dashboard","disabled":false,"hidden":false}]



//Wifi  + MQTT
#include <WiFi.h>
#include <PubSubClient.h>

//RFID SPI + RC522
#include <SPI.h>
#include <MFRC522.h>

// GPIO 2 D1
#define LED 2

/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
 *             MFRC522      ESP32     Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD             Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin       Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          GPIO27    9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      GPIO5     10            53        D10        10               10
 * SPI MOSI    MOSI         GPIO23    11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         GPIO19    12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          GPIO18    13 / ICSP-3   52        D13        ICSP-3           15
 *
[1] (1, 2) Configurable, typically defined as RST_PIN in sketch/program.
[2] (1, 2) Configurable, typically defined as SS_PIN in sketch/program.
[3] The SDA pin might be labeled SS on some/older MFRC522 boards
=============================================================================
*/
// SPI 
#define SS_PIN  5  // ESP32 pin GIOP5
#define RST_PIN 27 // ESP32 pin GIOP27


// WiFi
const char *ssid = "alex9ufo"; // Enter your Wi-Fi name
const char *password = "alex9981";  // Enter Wi-Fi password

// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";
const char *topic1 = "alex9ufo/esp32/led";
const char *topic2 = "alex9ufo/esp32/RFID";

const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

bool ledState = false;

WiFiClient espClient;
PubSubClient client(espClient);
MFRC522 rfid(SS_PIN, RST_PIN); // Create MFRC522 instance

long lastMsg = 0;
char msg[50];
String json = "";    
char jsonChar1[50];  //client.publish("alex9ufo/Esp32/RFID"

//宣告任務Task1
TaskHandle_t Task1;

// Wifi reconnect
unsigned long previousMillis = 0;
unsigned long interval = 30000;
//===========================================================
//任務1副程式Task1_senddata
void Task1_senddata(void * pvParameters ) {
  //無窮迴圈
  for (;;) {
    //偵測上傳旗標是否為true
    Serial.println("Reading RFID tag");
    if (rfid.PICC_IsNewCardPresent()) { // new tag is available
      if (rfid.PICC_ReadCardSerial()) { // NUID has been readed
        MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
        Serial.print("RFID/NFC Tag Type: ");
        Serial.println(rfid.PICC_GetTypeName(piccType));
        String rfidno="";
        // print UID in Serial Monitor in the hex format
        Serial.print("UID:");
        for (int i = 0; i < rfid.uid.size; i++) {
          Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
          Serial.print(rfid.uid.uidByte[i], HEX);
        }
        Serial.println();

        String json = printHex(rfid.uid.uidByte, rfid.uid.size);
        json.trim();
        json.toUpperCase();
        // Convert JSON string to character array
        json.toCharArray(jsonChar1, json.length()+1);
   
        if  (client.connected()) {
            Serial.print("Publish message: ");
            Serial.println(json);
            // Publish JSON character array to MQTT topic
            client.publish(topic2,jsonChar1);
             
          rfid.PICC_HaltA(); // halt PICC
          rfid.PCD_StopCrypto1(); // stop encryption on PCD
        }  
        else
        {
          Serial.print("MQTT not connected ");
        }
     
      }
    }


    else  
    {
      // PN532 probably timed out waiting for a card
      Serial.println("Timed out waiting for a card");
    }      
    //Task1休息,delay(X)不可省略
    delay(1000);
  }
}

//===========================================================
String printHex(byte *buffer, byte bufferSize) {
      String id = "";
      for (byte i = 0; i < bufferSize; i++) {
        id += buffer[i] < 0x10 ? "0" : "";
        id += String(buffer[i], HEX);
        id +=" ";
      }
      return id;
    }

//===========================================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect

    if (client.connect("esp32-client-")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("alex9ufo/esp32/led");
      client.subscribe("alex9ufo/esp32/RFID");      
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
      if (WiFi.status() != WL_CONNECTED)  {
        Serial.println("Reconnecting to WiFi...");
        WiFi.disconnect();
        WiFi.reconnect();
      }
    }
  }
}
//===========================================================
void callback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message: ");
    String message;
    for (int i = 0; i < length; i++) {
        message += (char) payload[i];  // Convert *byte to string
    }
    Serial.print(message);
    if (message == "on" && !ledState) {
        digitalWrite(LED, HIGH);  // Turn on the LED
        ledState = true;
    }
    if (message == "off" && ledState) {
        digitalWrite(LED, LOW); // Turn off the LED
        ledState = false;
    }
    Serial.println();
    Serial.println("-----------------------");
}
//===========================================================

void setup() {
    // Set software serial baud to 115200;
    Serial.begin(115200);
    delay(1000); // Delay for stability
    //======================================================
    // Connecting to a WiFi network
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to the WiFi network");

    // Setting LED pin as output
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);  // Turn off the LED initially
    //======================================================
    SPI.begin();           // Init SPI bus
    rfid.PCD_Init();    // Init MFRC522

    Serial.println(F("Ready!"));
    Serial.println(F("======================================================"));
    Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");


    // Connecting to an MQTT broker
    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String client_id = "esp32-client-";
        client_id += String(WiFi.macAddress());
        Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("Public HiveMQ MQTT broker (broker.mqtt-dashboard.com) connected");
        } else {
            Serial.print("Failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }

    // Publish and subscribe
    client.subscribe(topic1);
    //在核心0啟動任務1
    xTaskCreatePinnedToCore(
    Task1_senddata, /*任務實際對應的Function*/
      "Task1",        /*任務名稱*/
      10000,          /*堆疊空間*/
      NULL,           /*無輸入值*/
      0,              /*優先序0*/
      &Task1,         /*對應的任務變數位址*/
      0);             /*指定在核心0執行 */

}
//===========================================================
void loop() {
  if (!client.connected()) {
      reconnect();
      Serial.print(" client not connected  reconnect ");
      delay(200);
  }
  client.loop();
  // Process LED message

  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
    Serial.print(millis());
    Serial.println("Reconnecting to WiFi...");
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
    client.setCallback(callback);
  }

}
//===========================================================

沒有留言:

張貼留言

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

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