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)
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
- Signal Transmission: The RFID reader emits a radio signal via its antenna.
- 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).
- Data Exchange: The tag sends its unique identification data back to the reader.
- 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
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
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/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
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
- Download the Arduino IDE: Go to the Arduino Software page and download the IDE for your operating system.
- Install the Arduino IDE: Follow the installation instructions for your operating system.
Step 2: Install ESP32 Board Definitions
- Open Arduino IDE.
- 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.
- 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
- 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
- Install MFRC522 Library:
- Go to Sketch > Include Library > Manage Libraries.
- Search for "MFRC522" and install the MFRC522 library by GithubCommunity.
- 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
- Open Arduino IDE.
- Copy and Paste the Code
- Select the Correct Port:
- Go to Tools > Port and select the port to which your ESP32 is connected.
- 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
Step 1: Install Thonny IDE
- Download Thonny: Go to the Thonny IDE download page and download the version for your operating system.
- Install Thonny: Follow the installation instructions for your operating system.
Step 2: Install MicroPython on Your ESP32
- 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
- Open Thonny.
- 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
Step 1: Sign Up/Login to ThingSpeak
- Visit ThingSpeak: Go to the ThingSpeak website in your web browser.
- 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
- Create Channel: Once logged in, click on "Channels" in the top menu and then click on "My Channels".
- New Channel: Click on the "New Channel" button.
- 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
- API Keys: After creating the channel, go to the "API Keys" tab.
- Generate API Key: Click on "Generate API Key" to create a new API key for your channel.
- 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
- 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
- Run Your MicroPython Code: Upload and run your MicroPython code on your ESP32 device.
- 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:
/**********************************************************************************
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()