Smart RFID Cloud Integration Using Bharat Pi (Arduino IDE and Micropython)

by bharatpi in Circuits > Arduino

1171 Views, 14 Favorites, 0 Comments

Smart RFID Cloud Integration Using Bharat Pi (Arduino IDE and Micropython)

WhatsApp Image 2024-05-15 at 17.24.14_d48baec1.jpg
WhatsApp Image 2024-05-15 at 17.24.14_72ae1f7e.jpg

RFID stands for Radio-Frequency Identification. It is a technology used to automatically identify and track tags attached to objects using electromagnetic fields.

How RFID Works

  1. Signal Transmission: The RFID reader emits a radio signal via its antenna.
  2. Tag Activation: When an RFID tag comes within the range of the reader’s signal, it is activated (in the case of passive tags) or it transmits its stored information (in the case of active tags).
  3. Data Exchange: The tag sends its unique identification data back to the reader.
  4. Data Processing: The reader captures this data and sends it to a computer system for processing and storage.

Bharat Pi:

Bharat Pi is an Indian-made Internet of Things (IoT) prototyping platform designed to help students, developers, innovators and startups quickly build prototypes and ready-to-deploy products


Supplies

WhatsApp Image 2024-05-15 at 17.30.00_2d367183.jpg
WhatsApp Image 2024-05-15 at 17.31.21_a99c7c17.jpg

1 RFID Writer Module

2 Bharat Pi Module

https://bharatpi.net/product/bharat-pi-node-wifi/

(please click on the above link to buy the board)

Bharat Pi Boards

WhatsApp Image 2024-05-15 at 17.39.13_847af0bc.jpg

Bharat Pi Node WiFi is a specific model within the Bharat Pi product line designed for prototyping projects that involve WiFi connectivity

  • Microcontroller: ESP32 Wroom with 4MB memory . This chip provides processing power for your project.
  • Connectivity: Built-in WiFi and Bluetooth for wireless communication .
  • Storage: MicroSD card slot that supports up to 64GB of storage for data logging or program storage .
  • Programming: Compatible with Arduino IDE and microPython for programming the board .

The Bharat Pi Node WiFi is a good option if you're looking for an easy-to-use, single-board solution for building IoT projects that require WiFi connection. You can find more information and purchase the board directly from the Bharat Pi website 

https://bharatpi.net/

https://bharatpi.net/bharat-pi-node-wi-fi-board-pinout/

(click the above link for pin out diagram)

Pin Connection

SDA (SS) -> GPIO21

SCK -> GPIO 18 

MOSI -> GPIO 23

MISO -> GPIO 19

RST -> GPIO27

3.3V -> 3.3V pin

GND -> GND pin 

Arduino IDE Setup

Screenshot 2024-05-15 124006.png

Setting up the Arduino IDE for your ESP32 and RFID project involves several steps to ensure you have the correct libraries and board definitions. Below is a detailed guide to help you get started.

Step 1: Install the Arduino IDE

  1. Download the Arduino IDE: Go to the Arduino Software page and download the IDE for your operating system.
  2. Install the Arduino IDE: Follow the installation instructions for your operating system.

Step 2: Install ESP32 Board Definitions

  1. Open Arduino IDE.
  2. Add ESP32 Board Manager URL:
  • Go to File > Preferences.
  • In the "Additional Board Manager URLs" field, add the following URL:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json 
  • Click OK.
  1. Install ESP32 Boards:
  • Go to Tools > Board > Boards Manager.
  • Search for "ESP32" and click Install on the esp32 by Espressif Systems entry.

Step 3: Select Your ESP32 Board

  1. Select Board:
  • Go to Tools > Board.
  • Scroll down and select your ESP32 board model, e.g., ESP32 Wroom Da Module

Step 4: Install Required Libraries

  1. Install MFRC522 Library:
  • Go to Sketch > Include Library > Manage Libraries.
  • Search for "MFRC522" and install the MFRC522 library by GithubCommunity.
  1. Install HTTPClient Library:
  • The HTTPClient library is included by default with the ESP32 core, so you don't need to install it separately.

Step 5: Connect Your ESP32 and RFID Module

Step 6: Upload the Code

  1. Open Arduino IDE.
  2. Copy and Paste the Code
  3. Select the Correct Port:
  • Go to Tools > Port and select the port to which your ESP32 is connected.
  1. Upload the Code:
  • Click on the Upload button (right arrow icon).

Additional Tips

  • Serial Monitor: Use the Serial Monitor (Tools > Serial Monitor) to view debug messages and ensure everything is working correctly.
  • Troubleshooting: If you encounter any issues, double-check your wiring and ensure all libraries are correctly installed.



Micropython Setup

Screenshot 2024-05-15 141747.png

Step 1: Install Thonny IDE

  1. Download Thonny: Go to the Thonny IDE download page and download the version for your operating system.
  2. Install Thonny: Follow the installation instructions for your operating system.

Step 2: Install MicroPython on Your ESP32

  1. Download the MicroPython Firmware:
  • Go to the MicroPython download page for ESP32.
  • Download the latest stable .bin firmware file for ESP32.

Step 3: Erase the Flash Memory on ESP32:

  • Connect your ESP32 to your computer via USB.
  • Identify the serial port (COM port on Windows, /dev/ttyUSB0 or similar on Linux).
  • Run the following command, replacing <PORT> with your port (e.g., COM3, /dev/ttyUSB0):

Step 4: Upload MicroPython Firmware:

  • Run the following command, replacing <PORT> and <FIRMWARE> with your port and the path to the downloaded firmware

Step 5: Set Up Thonny for MicroPython

  1. Open Thonny.
  2. Configure the Interpreter:
  • Go to Tools > Options.
  • Select the Interpreter tab.
  • Choose MicroPython (ESP32) from the Interpreter dropdown menu.
  • Select the correct port for your ESP32.
  • Click OK.

Step 6: Connect and Test





ThingSpeak Setup

Screenshot 2024-05-15 124212.png

Step 1: Sign Up/Login to ThingSpeak

  1. Visit ThingSpeak: Go to the ThingSpeak website in your web browser.
  2. Sign Up/Login: If you don't have an account, click on "Sign Up" and follow the instructions to create an account. If you already have an account, log in using your credentials.

Step 2: Create a New Channel

  1. Create Channel: Once logged in, click on "Channels" in the top menu and then click on "My Channels".
  2. New Channel: Click on the "New Channel" button.
  3. Configure Channel:
  • Enter a name and description for your channel.
  • Define the fields you want to use for your data. For example, for your RFID data, you might have fields for RFID tag and student name.
  • Click on "Save Channel" to create the channel.

Step 3: Get Your API Key

  1. API Keys: After creating the channel, go to the "API Keys" tab.
  2. Generate API Key: Click on "Generate API Key" to create a new API key for your channel.
  3. Copy API Key: Copy the generated API key. You will need this API key in your code to send data to ThingSpeak.

Step 4: Configure Your MicroPython Code

  1. Update MicroPython Code: In your MicroPython code, replace the apiKey variable with the API key you copied from ThingSpeak.
api_key = "YOUR_API_KEY_HERE" 

Step 5: Send Data to ThingSpeak

  1. Run Your MicroPython Code: Upload and run your MicroPython code on your ESP32 device.
  2. Check ThingSpeak Channel: After running the code, go back to your ThingSpeak account and navigate to your channel to view the data being sent from your ESP32 device.

By following these steps, you should be able to set up ThingSpeak and send data from your ESP32 device to your ThingSpeak channel. Make sure to customize your channel fields and update your MicroPython code with the correct API key.

Arduino Code

please click the below link:

https://github.com/Bharat-Pi/iot-projects/blob/main/Bharat_Pi_RFID_and_Thingspeak/Bharat_Pi_RFID_and_Thingspeak.ino

/**********************************************************************************
RFID Module pin connection
SDA (SS) -> GPIO21
SCK ->  GPIO 18 
MOSI -> GPIO 23
MISO -> GPIO 19
RST -> GPIO27
3.3V -> 3.3V pin
GND -> GND pin 
***************************************************************************************/
#include <WiFi.h>
#include <HTTPClient.h>
#include <MFRC522.h>
#include <SPI.h>


#define SS_PIN 21
#define RST_PIN 27


MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance.


// Valid UIDs and corresponding student names
byte validUIDs[][4] = {
  {0xA3, 0x57, 0xB3, 0x30},  // UID of student 1
  {0x53, 0x15, 0x57, 0xC8},  // UID of student 2
  // Add more valid UIDs here
};
const char* studentNames[] = {
  "Bharatpi",  // Name of student 1
  "Welcome",   // Name of student 2
  // Add more student names here
};


const char* ssid = "smile123";
const char* password = "123456789";
const char* server = "http://api.thingspeak.com/update";
const char* apiKey = "1ZQ9LAB3G9CYY6GA";  // change the api key 


void setup() {
  Serial.begin(115200);
  SPI.begin();       // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522


  // Connect to Wi-Fi
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}


void loop() {
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }


  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }


  String rfid = "";
  // Read the RFID tag
  for (byte i = 0; i < mfrc522.uid.size; i++) {
    rfid += String(mfrc522.uid.uidByte[i], HEX);
  }
  rfid.toUpperCase();
  Serial.println("RFID tag: " + rfid);


  // Match the UID
  String studentName = "Unknown";
  for (byte i = 0; i < sizeof(validUIDs) / sizeof(validUIDs[0]); i++) {
    if (memcmp(mfrc522.uid.uidByte, validUIDs[i], mfrc522.uid.size) == 0) {
      studentName = studentNames[i];
      break;
    }
  }
  Serial.println("Student name: " + studentName);


  // Send data to ThingSpeak
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = String(server) + "?api_key=" + apiKey + "&field2=" + studentName + "&field1=" + rfid;
    Serial.println("URL: " + url); // Debugging URL
    http.begin(url);
    int httpCode = http.GET();
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("Response payload: " + payload); // Debugging payload
    } else {
      Serial.println("Error in HTTP request: " + String(http.errorToString(httpCode).c_str()));
    }
    http.end();
  } else {
    Serial.println("WiFi not connected");
  }


  delay(10000); // Send data every 10 seconds
}

Micropython Code

please click the below link:

https://github.com/Bharat-Pi/MicroPython/tree/main/Bharat_pi_RFID_Using_Thingspeak

import network
import urequests
from mfrc522 import MFRC522
from machine import Pin, SPI
from time import sleep


# RFID pin configuration
SCK = 18
MOSI = 23
MISO = 19
SDA = 21
RST = 27


# Initialize RFID reader
spi = SPI(1, baudrate=1000000, polarity=0, phase=0, sck=Pin(SCK), mosi=Pin(MOSI), miso=Pin(MISO))
rfid = MFRC522(spi, Pin(SDA), Pin(RST))


# Wi-Fi credentials
ssid = "smile123"
password = "123456789"


# ThingSpeak settings
server = "http://api.thingspeak.com/update"
api_key = "1ZQ9LAB3G9CYY6GA"


# Valid UIDs and corresponding student names
valid_uids = [
    [0xA3, 0x57, 0xB3, 0x30],  # UID of card 1
    [0x53, 0x15, 0x57, 0xC8],  # UID of card 2
    # Add more valid UIDs here
]


student_names = [
    "Bharatpi",  # Name of card 1
    "Welcome",   # Name of card 2
    # Add more student names here
]


# Connect to Wi-Fi
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    while not wlan.isconnected():
        sleep(0.5)
        print("Connecting to WiFi...")
    print("WiFi connected")
    print("IP address:", wlan.ifconfig()[0])


# Send data to ThingSpeak
def send_to_thingspeak(rfid, student_name):
    url = "{}?api_key={}&field1={}&field2={}".format(server, api_key, rfid, student_name)
    response = urequests.get(url)
    print("Response payload:", response.text)
    response.close()


# Read RFID tags
def read_rfid():
    print("Place your card to the reader")
    while True:
        (status, _) = rfid.request(rfid.REQIDL)
        if status == rfid.OK:
            (status, uid) = rfid.anticoll()
            if status == rfid.OK:
                rfid_str = "".join("{:02X}".format(i) for i in uid)
                print("RFID tag:", rfid_str)
                
                # Match the UID
                student_name = "Unknown"
                for i, valid_uid in enumerate(valid_uids):
                    if uid == valid_uid:
                        student_name = student_names[i]
                        break
                print("Student name:", student_name)
                
                # Send data to ThingSpeak
                send_to_thingspeak(rfid_str, student_name)
                sleep(10)  # Wait 10 seconds before next read


# Main function
def main():
    connect_wifi()
    read_rfid()


if __name__ == "__main__":
    main()