2019年8月9日 星期五

NodeMCU + RFID + MQTT + Node-RED

NodeMCU + RFID + MQTT + Node-RED
利用RFID rc522 reader讀取 mifare卡號,送至MQTT上。
用Node-RED 訂閱取得MQTT上刷卡卡號,並且顯示於Node-RED UI介面上。 可以使用 Node-RED UI上的 on LED ,off LED ,flash LED 控制 NodeMCU上的 LED on,off ,flash。




1) 使用 ESP8266 Node-MCU (Lolin) + RFID RC522 Reader讀取RFID Tag


 
接線如下
GND     = GND                  3.3V    = 3.3V
The following table shows the typical pin layout used:
Signal                  MFRC522     WeMos D1 mini     NodeMcu     Generic
RST/Reset           RST                D3 [1]                    D3 [1]          GPIO-0 [1]
SPI SS                 SDA [3]          D8 [2]                    D8 [2]          GPIO-15 [2]
SPI MOSI           MOSI              D7                          D7                GPIO-13
SPI MISO           MISO              D6                          D6                GPIO-12
SPI SCK              SCK                D5                          D5                GPIO-14
[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

程式如後


2) 啟動Node-RED (PC進入到CMD 模式)
C:\Users\alex\AppData\Roaming\npm\node-red.cmd


3) 打開 Chrome瀏覽器,網址列輸入 http://127.0.0.1:1880/,就可以打開 Node-RED,把Node-RED程式匯入




 4)匯入import前 就後面的程式用PC 筆記本程式存檔 再複製 貼到Node-RED上      (不可以用Wordpad) 


5)匯入程式


6)按Deploy
7) Debug 模式 與 UI 模式的切換



8)進入 UI 模式 控制LED ON/OFF/FLASH 與顯示RFID 感應資訊


9) 在Arduino IDE上  工具->串列監控視窗 可以檢視 UI送出的mseeage


10) 卡號的顯示


10). 其他畫面













ESP8266程式
=====================================================
/*
Many thanks to nikxha from the ESP8266 or WEMOSD1 forum
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include "MFRC522.h"

/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
Signal        MFRC522     WeMos D1 mini     NodeMcu     Generic
RST/Reset     RST         D3 [1]            D3 [1]      GPIO-0 [1]
SPI SS        SDA [3]     D8 [2]            D8 [2]      GPIO-15 [2]
SPI MOSI      MOSI        D7                D7          GPIO-13
SPI MISO      MISO        D6                D6          GPIO-12
SPI SCK       SCK         D5                D5          GPIO-14
[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 RST_PIN  D3     // RST-PIN für RC522 - RFID - SPI - D3
#define SS_PIN   D8     // SDA-PIN für RC522 - RFID - SPI - D8

// Update these with values suitable for your network.
//const char *ssid = "PTS-2F";
//const char *pass = "PTS6662594";
const char *ssid = "74170287";
const char *pass = "24063173";
//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network


#define MQTTid              ""                           //id of this mqtt client
#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker
#define MQTTport            1883                         //port of the mqtt broker
#define MQTTuser            "alex9ufo"                   //username of this mqtt client
#define MQTTpsw             "alex9981"                   //password of this mqtt client
//#define MQTTuser          "your_username"              //username of this mqtt client
//#define MQTTpsw           "your_password"              //password of this mqtt client
#define MQTTpubQos          2                            //qos of publish (see README)
#define MQTTsubQos          1                            //qos of subscribe

#define BUILTIN_LED        2                             // Arduino standard is GPIO13 but lolin nodeMCU is 2
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

struct RFIDTag {    // 定義結構
   byte uid[4];
   char *name;
};
//==================================
//先執行RFID_2程式確認卡號再來設定
// 初始化結構資料
// 將卡號變成代號Arduino....Raspberry Pi.....Espruino
//==================================
struct RFIDTag tags[] = {  // 初始化結構資料
   {{0x70,0x21,0xED,0x10}, "Alex9ufo"},
   {{0x44,0x51,0xBB,0x96}, "RaspberryPi"},
   {{0x15,0x8,0xA,0x53}, "Espruino"}
};

byte totalTags = sizeof(tags) / sizeof(RFIDTag);

//Variables
long lastMsg = 0;
char jsonChar[100];
String IDNo_buf="";
//=============================================================================
boolean pendingDisconnect = false;
void mqttConnectedCb(); // on connect callback
void mqttDisconnectedCb(); // on disconnect callback
void mqttDataCb(char* topic, byte* payload, unsigned int length); // on new message callback

WiFiClient wclient;
PubSubClient client(MQTTip, MQTTport, mqttDataCb, wclient);

//=============================================================================
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 mqttConnectedCb() {
  Serial.println("connected");

  // Once connected, publish an announcement...
  client.publish("alex9ufo/outTopic/RFID/json", jsonChar, MQTTpubQos, true); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic", MQTTsubQos);

}
//=============================================================================
void mqttDisconnectedCb() {
  Serial.println("disconnected");
}
//=============================================================================
void mqttDataCb(char* topic, byte* payload, unsigned int length) {

  /*
  you can convert payload to a C string appending a null terminator to it;
  this is possible when the message (including protocol overhead) doesn't
  exceeds the MQTT_MAX_PACKET_SIZE defined in the library header.
  you can consider safe to do so when the length of topic plus the length of
  message doesn't exceeds 115 characters
  */
  char* message = (char *) payload;
  message[length] = 0;
  //String message;
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(message);
  String message1;
  for (int i = 0; i < length; i++) {
    message1 = message1 + (char)payload[i];  //Conver *byte to String
  }
  //Serial.print(message);
  if(message1 == "#on") {digitalWrite(BUILTIN_LED,LOW);}   //LED on  
  if(message1 == "#off") {digitalWrite(BUILTIN_LED,HIGH);} //LED off
  if(message1== "#flash") {
      digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
      // but actually the LED is on; this is because
      for (int i=0; i <=5; i++){
          digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
          delay(500);
          digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that HIGH is the voltage level
          delay(500);
      } //for (int
      digitalWrite(BUILTIN_LED, HIGH);
   } // if(message== "#flashLED")

  /*
  // Switch on the LED if an 1 was received as first character
  if (message[0] == '0') {
     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
     // but actually the LED is on; this is because
     Serial.println("Received 0 , Send LOW TO BuildIn_LED");
    }
   if (message[0] == '1') {
     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
     // but actually the LED is on; this is because
     Serial.println("Received 1 , Send HIGH TO BuildIn_LED");
   }
    if (message[0] == '2') {
     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
     // but actually the LED is on; this is because
     Serial.println("Received 2 , Flashing BuildIn_LED ");
     for (int i=0; i <=5; i++){
       digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
       delay(500);
       digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that HIGH is the voltage level
       delay(500);
      } //for (int
       digitalWrite(BUILTIN_LED, HIGH);
   } //if (message[0] == '2')
   */
}
//======================================================
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

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

}
//======================================================
void setup() {
  Serial.begin(115200);
  setup_wifi();
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println(F("Booting...."));
  SPI.begin();           // Init SPI bus
  mfrc522.PCD_Init();    // Init MFRC522
  Serial.println(F("Ready!"));
  Serial.println(F("======================================================"));
  Serial.println(F("Scan for Card and print UID:"));
}
//======================================================
void process_mqtt() {
  if (WiFi.status() == WL_CONNECTED) {
    if (client.connected()) {
      client.loop();
    } else {
    // client id, client username, client password, last will topic, last will qos, last will retain, last will message
      if (client.connect(MQTTid, MQTTuser, MQTTpsw, MQTTid "/status", 2, true, "0")) {
          pendingDisconnect = false;
          mqttConnectedCb();
      }
    }
  } else {
    if (client.connected())
      client.disconnect();
  }
  if (!client.connected() && !pendingDisconnect) {
    pendingDisconnect = true;
    mqttDisconnectedCb();
  }
}
//======================================================
void loop() {
  process_mqtt();
  long now = millis();
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { // 如果出現新卡片就讀取卡片資料
      byte *id = mfrc522.uid.uidByte;   // 取得卡片的UID
      byte idSize = mfrc522.uid.size;   // 取得UID的長度
      bool foundTag = false;            // 是否找到紀錄中的標籤,預設為「否」。
      byte i=0;
      for (i=0; i<totalTags; i++) {
        if (memcmp(tags[i].uid, id, idSize) == 0) {
          Serial.print(F("Card UID:"));
          Serial.println(tags[i].name);  // 顯示標籤的名稱
          foundTag = true;  // 設定成「找到標籤了!」
          break;            // 退出for迴圈
        }
      }

      if (!foundTag) {    // 若掃描到紀錄之外的標籤,則顯示"Wrong card!"。
        Serial.println("Wrong card!");
      }

    mfrc522.PICC_HaltA();  // 讓卡片進入停止模式   

    //Serial.println(tags[i].name);
    IDNo_buf="";
    IDNo_buf=tags[i].name;
    // Convert data to JSON string
    String json =
    "{\"data\":{"
    "\"RFID_No\": \"" + IDNo_buf + "\"}"
    "}";
    // Convert JSON string to character array
    json.toCharArray(jsonChar, json.length()+1);
 
    if  (client.connected()) {
         Serial.print("Publish message: ");
         Serial.println(json);
         // Publish JSON character array to MQTT topic
         client.publish("alex9ufo/outTopic/RFID/json",jsonChar);
    }
    /*
     delay(100);
     String IDNo = printHex(mfrc522.uid.uidByte, mfrc522.uid.size);
     // Show some details of the PICC (that is: the tag/card)
     if ((IDNo != IDNo_buf) && (now - lastMsg > 5000)) {  //不同卡片 或是 等5秒
         lastMsg = now;
         Serial.print(F("Card UID:"));
         Serial.println(IDNo);
         //Serial.println(IDNo_buf);
 
         IDNo_buf="";
         IDNo_buf=IDNo;
         // Convert data to JSON string
         String json =
         "{\"data\":{"
         "\"RFID_No\": \"" + IDNo + "\"}"
         "}";
         // Convert JSON string to character array
         json.toCharArray(jsonChar, json.length()+1);
 
         if  (client.connected()) {
              Serial.print("Publish message: ");
              Serial.println(json);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/outTopic/RFID/json",jsonChar);
         }
      } // if ((IDNo != IDNo_buf) || (now - lastMsg > 5000))
      */
  }  // if (mfrc522.PICC_IsNewCardPresent()

}   //Loop
//======================================================

Node-RED程式
======================================================
[{"id":"36b9ac19.468a04","type":"mqtt in","z":"a47b5494.3eb618","name":"","topic":"alex9ufo/outTopic/RFID/json","qos":"2","broker":"40bf4d5e.0395f4","x":340,"y":140,"wires":[["485f884f.203ce8","f44190ce.e2ea1"]]},{"id":"f44190ce.e2ea1","type":"function","z":"a47b5494.3eb618","name":"jason+??蝘?,"func":"var date = new Date();\nvar h = date.getHours();\nvar m = date.getMinutes();\nvar s = date.getSeconds();\nif(h<10){\n    h = '0'+h;\n}\nif(m<10){\n    m = '0' + m;\n}\nif(s<10){\n    s = '0' + s;\n}\nmsg.payload = 'Time:(' + h + ':' + m + ':' + s + ')'+ msg.payload ;\nreturn msg;\n","outputs":1,"noerr":0,"x":600,"y":100,"wires":[["b4dc5dae.5e7a5"]]},{"id":"b4dc5dae.5e7a5","type":"ui_text","z":"a47b5494.3eb618","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"name":"","label":"MQTT_send_Message","format":"{{msg.payload}}","layout":"row-center","x":800,"y":100,"wires":[]},{"id":"485f884f.203ce8","type":"debug","z":"a47b5494.3eb618","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":590,"y":180,"wires":[]},{"id":"cbe61db9.a111f","type":"mqtt out","z":"a47b5494.3eb618","name":"","topic":"alex9ufo/inTopic","qos":"1","retain":"false","broker":"40bf4d5e.0395f4","x":560,"y":260,"wires":[]},{"id":"fdce570a.70c9a8","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"ON_LED","color":"white","bgcolor":"","icon":"fa-circle","payload":"#on","payloadType":"str","topic":"","x":280,"y":260,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"7789eb7e.2785d4","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"off_LED","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#off","payloadType":"str","topic":"","x":280,"y":320,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"b13346c4.b6fb38","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"flash_LED","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#flash","payloadType":"str","topic":"","x":290,"y":380,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"be2f332d.8a81c","type":"debug","z":"a47b5494.3eb618","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":550,"y":360,"wires":[]},{"id":"40bf4d5e.0395f4","type":"mqtt-broker","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":15,"cleansession":true,"birthQos":"0","willQos":"0"},{"id":"e4b1387a.934b88","type":"ui_group","z":"","name":"Control led ESP8266 (ESP32)","tab":"8b6381a9.6f9d6","order":1,"disp":true,"width":"15","collapse":false},{"id":"8b6381a9.6f9d6","type":"ui_tab","name":"Tab 1","icon":"dashboard","order":1}]


ESP8266程式感應後 將16進制卡號 變成代號

//==================================
//先執行RFID_2程式確認卡號再來設定
// 初始化結構資料
// 將卡號變成代號Arduino....Raspberry Pi.....Espruino
//==================================
struct RFIDTag tags[] = {  // 初始化結構資料
   {{0x70,0x21,0xED,0x10}, "Alex9ufo"},
   {{0x44,0x51,0xBB,0x96}, "RaspberryPi"},
   {{0x15,0x8,0xA,0x53}, "Espruino"}
};

程式RFID_2.ino
=================================================
/*
Many thanks to nikxha from the ESP8266 forum
*/
#include <ESP8266WiFi.h>
#include <SPI.h>
#include <MFRC522.h>
//#include "MFRC522.h"

/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
Signal        MFRC522     WeMos D1 mini     NodeMcu     Generic
RST/Reset     RST         D3 [1]            D3 [1]      GPIO-0 [1]
SPI SS        SDA [3]     D8 [2]            D8 [2]      GPIO-15 [2]
SPI MOSI      MOSI        D7                D7          GPIO-13
SPI MISO      MISO        D6                D6          GPIO-12
SPI SCK       SCK         D5                D5          GPIO-14
[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 RST_PIN  D3     // RST-PIN für RC522 - RFID - SPI - D3
#define SS_PIN   D8     // SDA-PIN für RC522 - RFID - SPI - D8

// Update these with values suitable for your network.
const char *ssid = "PTS-2F";
const char *pass = "pts6662594";
//const char *ssid = "74170287";
//const char *pass = "24063173";
//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network

MFRC522 mfrc522(SS_PIN, RST_PIN);  // 建立MFRC522物件

void setup() {
  Serial.begin(9600);
  Serial.println("RFID reader is ready!");

  SPI.begin();
  mfrc522.PCD_Init();   // 初始化MFRC522讀卡機模組
}

void loop() {
    // 確認是否有新卡片
    if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
      byte *id = mfrc522.uid.uidByte;   // 取得卡片的UID (第20行)
      byte idSize = mfrc522.uid.size;   // 取得UID的長度

      Serial.print("PICC type: ");      // 顯示卡片類型
      // 根據卡片回應的SAK值(mfrc522.uid.sak)判斷卡片類型
      MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);   // (第25行)
      Serial.println(mfrc522.PICC_GetTypeName(piccType));

      Serial.print("UID Size: ");       // 顯示卡片的UID長度值
      Serial.println(idSize);

      for (byte i = 0; i < idSize; i++) {  // 逐一顯示UID碼
        Serial.print("id[");
        Serial.print(i);
        Serial.print("]: ");
        Serial.println(id[i], HEX);       // 以16進位顯示UID值
      }
      Serial.println();

      mfrc522.PICC_HaltA();  // 讓卡片進入停止模式
    }
}
//=============================================================================




沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

 WOKWI DHT22 & LED , Node-Red + SQLite database Node-Red程式 [{"id":"6f0240353e534bbd","type":"comment&...