Overview
RFID tags provide a simple and cost effective way to trigger an action. By either using a credit card sized tag or keychain fob, the Internet of LEGO city can respond in a number of ways. For instance, a card ID can unlock a door, grant access to the train system or record an identity.
As a side bonus, my two year old loves playing with these RFID tags! So, I built a fun project that makes sounds, flashes lights and enables various functions within the IoL City. I built a LEGO box to contain the components, used an ESP8266 dev board for the electronics and send the messages over WiFi using MQTT. Node-RED then acts as the orchestrator to verify the card and trigger an action.
Components
- Microcontroller w/ WiFi
- RFID
- MF-RC522
- “The MFRC522 is a highly integrated reader/writer IC for contactless communication at 13.56 MHz. The MFRC522 reader supports ISO/IEC 14443 A/MIFARE and NTAG.”
- More Info
- MF-RC522
- MQTT Client
- Homie
- “Homie for ESP8266 is an ESP8266 for Arduino implementation ofHomie, a thin and simple MQTT convention for the IoT. More than that, it’s also a full-featured framework to get started with your IoT project very quickly. Simply put, you don’t have to manage yourself the connection/reconnection to the Wi-Fi/MQTT. You don’t even have to hard-code credentials in your sketch: this can be done using a simple JSON API. Everything is handled internally, by Homie for ESP8266.”
- Homie
- MQTT Broker
- Mosquitto
- “Eclipse Mosquitto™ is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 3.1 and 3.1.1. MQTT provides a lightweight method of carrying out messaging using a publish/subscribe model. This makes it suitable for “Internet of Things” messaging such as with low power sensors or mobile devices such as phones, embedded computers or microcontrollers like the Arduino.”
- Mosquitto
- Server
- Raspberry Pi
- “The Raspberry Pi is a tiny and affordable computer that you can use to learn programming through fun, practical projects.”
- Raspberry Pi
- IoT programming environment
- Node-RED
- “Node-RED is a tool for wiring together hardware devices, APIs and online services in new and interesting ways.”
- Node-RED
Construction
Circuit
This wiring diagram and sample Arduino code was the basis for the circuit. I then added a reset button, speaker and two LEDs to the ports specified in the code.
LEGO Box
The LEGO box was constructed with solid base plate and long technic bricks for strength. A panel opens up to expose the WeMos D1 connections. The RFID tag was held in place with a little bit of Blu Tack.
MQTT w/ Homie
Many IoT projects use MQTT as a Publish/Subscription way of communicating. This can easily be implemented on an Arduino compatible system using a simplepubsublclient library developed by Nick o’Leary.
This project hopes to expand beyond simply using MQTT, by appreciating some sense of standard for scalability and maintenance. This is how I discovered theHomie convention, developed by Marvin Roger. What’s nice about this implementation is that it handles many of the tedious admin tasks for managing the connection, sending updates, storing state, OTA, and initializing the device with the network specific configurations.
Getting started with Homie
- A device Arduino library built for the ESP8266 at marvinroger/homie-esp8266
- An opinionated Web UI built with Node.js at marvinroger/homie-server
- Some Node-RED nodes for automation at marvinroger/node-red-contrib-homie
- Configuration assistant at https://github.com/marvinroger/homie-esp8266/tree/gh-pages
This project uses a WeMos D1-Mini, which will support the ESP8266 version. By including this library in the code, the device will boot up in a special configuration mode. It will then advertise its own WiFi SSID, which you must first join to configured. At that point, you can either use the API, web page or Android App to push the network and device settings. These configurations include the name of the device, MQTT broker, base topic, and WiFi settings.
I’ve used web based configuration assistant to get started.
- Download the web UI
- Turn on the Arduino/ESP device, and connect to its SSID “Homie-aabbccdd”, where the password and specific name are that of the MAC address. So, I would use “aabbccdd” as the password in this example.
- Once connected to the SSID, open the index.html file that is contained in the web UI download. This will run a local web application to scan for the Homie device and provide a setup guide.
Firmware
Download Code from GitHub (includes pitches.h)
This firmware implements Homie to deliver RFID scan results via MQTT. Two LEDs and a speaker are attached to the WeMos D1-mini, for user feedback.
One unique style of this code is that the setup() and loop() functions are used to begin the setupHandler() and loopHandler() functions, for Homie. The reason for this is that Homie will keep track of the connection state and manage the state of the various properties. Its been advised to avoid any sort of blocking activity (i.e.delay(1000)) within the standard loop() function to avoid disrupting the network mechanics.
- void setup() {
- Homie.setFirmware(“rfid”, “1.0.0”);
- Homie.registerNode(rfidNode);
- Homie.setSetupFunction(setupHandler);
- Homie.setLoopFunction(loopHandler);
- rfidNode.subscribe(“validate”, verifyHandler);
- Homie.setup();
- }
- void loop() {
- Homie.loop();
- }
The actual scanning of the RFID card is handled by three functions. Within each loop iteration, the RFID scanner looks for a card then prints the UID from its buffer to a byte array.
- // Select one of the cards
- if ( ! mfrc522.PICC_ReadCardSerial()) {
- Serial.print(“found card…”);
- delay(50);
- return;
- }
- // Process card
- Serial.print(F(“Card UID:”));
- dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
- }
- // RFID: dump a byte array as hex values to Serial, then send to validation routine.
- void dump_byte_array(byte *buffer, byte bufferSize) {
- String uid;
- const long interval = 1000;
- for (byte i = 0; i < bufferSize; i++) {
- Serial.print(buffer[i] < 0x10 ? ” 0″ : ” “);
- Serial.print(buffer[i], HEX);
- uid = uid + String(buffer[i], HEX);
- }
- if(uid){
- validate(uid);
- }
- }
The Full Code will pull in the Homie library and a pitches.h library. The pitches file simply maps western musical tones (i.e. a piano range) to frequencies for easy incorporation into projects with sound.
The code is heavily commented and the functions are typically in the order of execution, where possible. Much of the code is cluttered with turning on lights and sounds (which could be endlessly tweaked and I’m guilty of wasting too much time on that).
- /*
- * RFID Scanner with audio and lights
- *
- * Communication via WiFi & MQTT using Homie.h
- * The ID will be sent to the MQTT topic.
- * When a success verification occurs, the lights and speaker will be activated
- * depending on the value.
- *
- *
- * Written by Cory Guynn
- * www.InternetOfLEGO.com
- * 2016
- *
- */
- // Networking – MQTT using Homie
- // https://github.com/marvinroger/homie/tree/master
- #include <Homie.h>
- HomieNode rfidNode(“RFID-1”, “sensor”);
- // Audio
- #include “pitches.h”
- // RFID
- #include “MFRC522.h”
- #define RST_PIN 15 // RST-PIN for RC522 – RFID – SPI – Modul GPIO15
- #define SS_PIN 2 // SDA-PIN for RC522 – RFID – SPI – Modul GPIO2
- MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
- // LEDs and Speaker
- const int PIN_RESET = 0; //D3 WeMos ~ This pin will flash WeMos when held low 5s
- const int PIN_RED = 16; //D0 WeMos
- const int PIN_GREEN = 15; //D8 WeMos
- const int PIN_SPEAKER = 5; //D1 WeMos
- // Standard Functions
- void setup() {
- Homie.setFirmware(“rfid”, “1.0.0”);
- Homie.registerNode(rfidNode);
- Homie.setSetupFunction(setupHandler);
- Homie.setLoopFunction(loopHandler);
- rfidNode.subscribe(“validate”, verifyHandler);
- Homie.setup();
- }
- void loop() {
- // all loop activity is handled by Homie, to ensure connectivity and prevent blocking activity that could disrupt communication
- Homie.loop();
- }
- void setupHandler() {
- // this replaces the traditional “setup()” to ensure connecitvity and handle OTA
- // RFID and Console
- Serial.begin(9600); // Initialize serial communications
- SPI.begin(); // Init SPI bus
- mfrc522.PCD_Init(); // Init MFRC522
- // sound beep
- tone(PIN_SPEAKER,NOTE_C1,250);
- delay(50);
- tone(PIN_SPEAKER,NOTE_E1,250);
- delay(50);
- tone(PIN_SPEAKER,NOTE_C1,250);
- delay(50);
- noTone(PIN_SPEAKER);
- // initialize LEDs
- pinMode(PIN_RED, OUTPUT);
- pinMode(PIN_GREEN, OUTPUT);
- digitalWrite(PIN_RED, HIGH);
- digitalWrite(PIN_GREEN, HIGH);
- delay(1000);
- digitalWrite(PIN_GREEN, LOW);
- }
- // Global Timer
- unsigned long previousMillis = 0;
- int interval = 2000;
- void loopHandler() {
- // Look for new RFID cards
- if ( ! mfrc522.PICC_IsNewCardPresent()) {
- //Serial.print(“scanning”);
- delay(50);
- return;
- }
- // scan the cards. Put in a non-blocking delay to avoid duplicate readings
- unsigned long currentMillis = millis();
- if (currentMillis – previousMillis >= interval) {
- previousMillis = currentMillis;
- // do non-blocking thing here
- // Select one of the cards
- if ( ! mfrc522.PICC_ReadCardSerial()) {
- Serial.print(“found card…”);
- delay(50);
- return;
- }
- // Process card
- Serial.print(F(“Card UID:”));
- dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
- }
- }
- // RFID: dump a byte array as hex values to Serial, then send to validation routine.
- void dump_byte_array(byte *buffer, byte bufferSize) {
- String uid;
- const long interval = 1000;
- for (byte i = 0; i < bufferSize; i++) {
- Serial.print(buffer[i] < 0x10 ? ” 0″ : ” “);
- Serial.print(buffer[i], HEX);
- uid = uid + String(buffer[i], HEX);
- }
- if(uid){
- validate(uid);
- }
- }
- // validate card UID by sending to server via MQTT
- void validate(String uid){
- Serial.print(“validating card: “);
- Serial.println(uid);
- // set RFID uid property to be sent via MQTT
- Homie.setNodeProperty(rfidNode, “uid”, uid, true);
- // Turn both LEDs on
- digitalWrite(PIN_RED, HIGH);
- digitalWrite(PIN_GREEN, HIGH);
- // play sounds
- tone(PIN_SPEAKER,NOTE_D1,50);
- delay(20);
- tone(PIN_SPEAKER,NOTE_D1,50);
- noTone(PIN_SPEAKER);
- digitalWrite(PIN_GREEN, LOW);
- }
- // Receive response from server via MQTT
- bool verifyHandler(String response) {
- Serial.print(“verifyHandler “);
- Serial.println(response);
- tone(PIN_SPEAKER,NOTE_C3,100);
- digitalWrite(PIN_RED, LOW);
- digitalWrite(PIN_GREEN, LOW);
- delay(250);
- if (response == “granted”) {
- Serial.println(“card accepted”);
- Homie.setNodeProperty(rfidNode, “validate”, “granted”, true);
- digitalWrite(PIN_GREEN, HIGH);
- tone(PIN_SPEAKER,NOTE_C3,250);
- delay(250);
- tone(PIN_SPEAKER,NOTE_C4,500);
- noTone(PIN_SPEAKER);
- delay(1000);
- digitalWrite(PIN_GREEN, LOW);
- } else if (response == “denied”) {
- Serial.print(“card denied”);
- Homie.setNodeProperty(rfidNode, “validate”, “denied”, true);
- digitalWrite(PIN_RED, HIGH);
- tone(PIN_SPEAKER,NOTE_C3,250);
- delay(250);
- digitalWrite(PIN_RED, LOW);
- tone(PIN_SPEAKER,NOTE_G2,500);
- delay(250);
- noTone(PIN_SPEAKER);
- digitalWrite(PIN_RED, HIGH);
- delay(1000);
- } else {
- digitalWrite(PIN_RED, HIGH);
- Serial.println(“unexpected response: “);
- Homie.setNodeProperty(rfidNode, “validate”, “unexpected”, true);
- Serial.print(response);
- tone(PIN_SPEAKER,NOTE_A2,500);
- delay(250);
- digitalWrite(PIN_RED, LOW);
- tone(PIN_SPEAKER,NOTE_A2,500);
- return false;
- }
- digitalWrite(PIN_RED, HIGH);
- return true;
- }
Node-RED
Flow
This Node-RED flow demonstrates various ways of using the RFID uid to trigger workflows and to send access messages back to the RFID scanner.
Workflow
The basis for this flow starts with subscribing to the MQTT topic for the RFID tag. In my scenario, the topic happened to be “sensors/e1b47aeo/RFID-1/uid“. Themsg.payload will contain the uid for the scanned tag. A switch node will then provide several outputs based on a condition, which happens to be the uid.
Access
I’ve decided to send all known uid’s to a function, which sets the msg.payload to “granted”. This in turn, will display a pop-up message on the node-red-dashboardUI, which displays the uid and whether or not the card was “granted”.
Disco & Cinema
All uid‘s that were granted will be sent to a link node, which allows me to connect it to various other flows. For example, I have sent a link to my IoL City version of a “Hello World”, which triggers disco lights in the local IoL City club and turns on a rainbow of marquee lights at the LEGO Palace Cinema.
Train Routine
A specific uid will trigger a flow to run a LEGO Horizon Express train for 5 seconds. This works because I hacked the train with a NodeMCU to control it via MQTT. See this article for all the details.
UI
The UI is provided by a handy Node-RED node, node-red-dashboard, which uses AngularJS to quickly build UI widgets. The dashboard will represent the RFID data in three ways.
- RFID Status
- Listen for any MQTT messages emitted by Homie. These are built-in with the Homie library and will periodically send messages relating to the state of the Homie node. This includes the device ID, IP, signal strength, defined properties, etc.
- The MQTT messages are stored in a context object, which is then sent to the UI node when the states change.
- RFID Event Log
- This UI widget will listen for any MQTT message emitted from the RFID scanner and shift register it into a context array, which is then delivered to aUI template node leveraging the ng-repeat AngularJS directive to simulate a console screen.
- RFID Notification
- A notification UI node is used to instantly create a pop-up or “toast” message on the UI dashboard with the recently scanned uid and if it was granted or denied.
Success!
This was a fun project with plenty of options to expand upon. The primary goal was to understand how an RFID scanner can be used with a EPS8266 and Node-RED. Using Homie was a great way to formalize a MQTT strategy. And finally, the newly embraced node-red-dashboard, demonstrates how you can quickly build a dashboard to start visualizing your data.
Final Thoughts
It’s common to use an RFID for security purposes. It would be expected to use MQTT with authentication and SSL or some secured transmission. This RFID scanner could also work really well in a more traditional REST framework. I almost wrote this project using the aREST Arduino library, but I was curious how to implement Homie… so this was a personal goal above all.
What’s also really interesting about this project and many other Internet of LEGO projects, is the reality that: Input + function = Output. I happened to use an RFID scanner for this project, but it could be any button, temperature sensor, web API or basic schedule that schedules a workflow. There are various ways to abstract this, like Zapier or IFTTT, web server/client paradigm or machine to machine communication. Once you understand the basic concept of IoT, the possibilities are endless (if you have enough LEGOs and electronics in my case).
Video
the original post is from http://www.internetoflego.com/rfid-scanner-wemos-rc522-mqtt/
Leave a Reply
You must be logged in to post a comment.