2023年7月11日 星期二

新實驗1-2 ESP32 + RFID + MQTT Explorer + Node-Red (控制LED 顯示RFID 卡號)

 新實驗1-2 ESP32 + RFID + MQTT Explorer +  Node-Red (控制LED 顯示RFID 卡號)





[{"id":"ea7eb653aba7166b","type":"ui_button","z":"8b3d0d99cede247a","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":160,"y":100,"wires":[["1c7d8b3b113d3fb6","c41ab00faf5fe4f8","8995dd76485a40eb"]]},{"id":"9618516c1740acc9","type":"ui_button","z":"8b3d0d99cede247a","name":"","group":"d783cb980c3979fc","order":0,"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":160,"y":140,"wires":[["1c7d8b3b113d3fb6","c41ab00faf5fe4f8","8995dd76485a40eb"]]},{"id":"1c7d8b3b113d3fb6","type":"mqtt out","z":"8b3d0d99cede247a","name":"Control LED","topic":"alex9ufo/esp32/led","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":410,"y":100,"wires":[]},{"id":"3981dbbec123a24d","type":"comment","z":"8b3d0d99cede247a","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":290,"y":40,"wires":[]},{"id":"c41ab00faf5fe4f8","type":"ui_audio","z":"8b3d0d99cede247a","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":400,"y":180,"wires":[]},{"id":"8995dd76485a40eb","type":"ui_text","z":"8b3d0d99cede247a","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":470,"y":140,"wires":[]},{"id":"0ee6109b1102f582","type":"ui_audio","z":"8b3d0d99cede247a","name":"","group":"d783cb980c3979fc","voice":"en-US","always":"","x":400,"y":340,"wires":[]},{"id":"17ecde715c8cb925","type":"mqtt in","z":"8b3d0d99cede247a","name":"RFID Card","topic":"alex9ufo/esp32/RFID","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":180,"y":400,"wires":[["0ee6109b1102f582","98aca87ee5727875","df8f5f01e0b4123d"]]},{"id":"98aca87ee5727875","type":"debug","z":"8b3d0d99cede247a","name":"debug 94","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":400,"y":420,"wires":[]},{"id":"0351af250ce1d035","type":"comment","z":"8b3d0d99cede247a","name":"Node-Red  subscribe HiveMQ Broker  , ESP32發行","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":280,"y":280,"wires":[]},{"id":"df8f5f01e0b4123d","type":"ui_text","z":"8b3d0d99cede247a","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"Node-RED 訂閱MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":460,"y":380,"wires":[]},{"id":"d783cb980c3979fc","type":"ui_group","name":"Demo","tab":"0449b3b1fea99d52","order":1,"disp":true,"width":"6","collapse":false},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"Storing IOT Data ","tab":"eeb8e179.a47a4","order":1,"disp":true,"width":"6","collapse":true},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"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":"eeb8e179.a47a4","type":"ui_tab","name":"eWeLink","icon":"dashboard","disabled":false,"hidden":false}]


#include <WiFi.h>
#include <PubSubClient.h>
#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
=============================================================================
*/

#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[100];  //client.publish("alex9ufo/Esp32/RFID"
//===========================================================
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);
      }
      return id;
    }
//===========================================================
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);

}
//===========================================================
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 loop() {
    client.loop();
    delay(100); // Delay for a short period in each loop iteration
    long now = millis();
    if (now - lastMsg > 5000) {
      Serial.println("Reading RFIF card");
      lastMsg = now;
      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));

          // 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);
          // 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

        }
      }
       
  }

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









沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...