In today’s blog we are going to make raspberry pi attendance system.
WHAT YOU NEED:
RC522 RFID Reader
16 × 2 LCD display
Micro SD card
Preparing Raspbian for your RFID Attendance System
1. To start, we will first ensure that everything is up to date on our Raspbian installation by running the following two commands on the Raspberry Pi.
sudo apt-get update sudo apt-get upgrade
2. We will now install all the packages that we will be relying on for the next few sections.
Let’s begin by installing build-essential, git,python3-dev, python3-pip, and python3-smbus by running the command below.
sudo apt-get install build-essential git python3-dev python3-pip python3-smbus
Building the 16×2 LCD Display Circuit
1. To start our tutorial, we will first begin setting up the 16×2 LCD. We will be quickly running through the process of setting this all up. If you want to learn more you can check out our tutorial on the 16×2 LCD Display.
For this section of the tutorial make sure that you have the following ready to go.
- 8 pieces of Male to Male Breadboard Wire
- 8 pieces of Male to Female Breadboard Wire
- 16×2 LCD Display
- 10k Ohm Potentiometer
2. Once you have all the parts required, you can start assembling the circuit by observing the diagrams and steps below.
Connecting the LCD to your Raspberry Pi is a pretty simple process if you follow our guide. We have included the physical pin number for each connection that you need to make.
To begin with, let’s connect up our various components with the breadboard.
- 5V (Physical Pin 2) to breadboard positive rail
- Ground (Physical Pin 6) to breadboard ground rail
- Place the 16×2 LCD Display into the right side of the breadboard
- Place the potentiometer into the left side of the breadboard next to the LCD Display.
- Connect the left pin of the potentiometer to the ground rail
- Connect the right pin of the potentiometer to the positive rail
3. Now begin connecting the LCD display to your Raspberry Pi.
- Pin 1 of LCD (Ground) to breadboard ground rail
- Pin 2 of LCD (VCC / 5V) to breadboard positive rail
- Pin 3 of LCD (V0) to middle wire of the potentiometer
- Pin 4 of LCD (RS) to GPIO4 (Physical Pin 7)
- Pin 5 of LCD (RW) to breadboard groundrail
- Pin 6 of LCD (EN) to GPIO24 (Physical Pin 18)
- Pin 11 of LCD (D4) to GPIO23 (Physical Pin 16)
- Pin 12 of LCD (D5) to GPIO17 (Physical Pin 11)
- Pin 13 of LCD (D6) to GPIO18 (Physical Pin 12)
- Pin 14 of LCD (D7) to GPIO22 (Physical Pin 15)
- Pin 15 of LCD (LED +) to breadboard positive rail
- Pin 16 of LCD (LED -) to breadboard ground rail
- Testing the 16×2 LCD Display1. Now that the circuit has been set up let’s go ahead and test it to ensure that everything was wired correctly.To start, go ahead and clone the Adafruit CharLCD library that we will be utilizing for this project. If your display board uses the HD44780 controller, then it will work with no issues.To clone the library to your Raspberry Pi run the following command on it.
git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git
- 2. Now with the library cloned to our Raspberry Pi, we need to run the setup script. This script will install the library so that any Python scripts can utilize it.Run the following two commands to move into the newly cloned directory and run the setup.py script.
cd ./Adafruit_Python_CharLCD sudo python3 setup.py install
- 3. With the library installed to the Raspberry Pi, we need to go ahead and edit an example file. We need to do this to test the circuit as we are using different pins to what the example utilizes.Begin editing the file by running the following command.
- 4. In this file, find the “# Raspberry Pi pin configuration:” section and change it so that the values match what we have below.
# Raspberry Pi pin configuration: lcd_rs = 4 lcd_en = 24 lcd_d4 = 23 lcd_d5 = 17 lcd_d6 = 18 lcd_d7 = 22Once the changes are made, save the file by pressing CTRL + X then Y and then ENTER.
- 5. Now before we go ahead and run our new modified example we will need to install the Raspberry Pi’s GPIO Python library.To install the required library run the following command.
sudo pip3 install RPi.GPIO
- 6. To test that everything is working lets now run that python script by running the command below. If everything is working as it should, you should now see text displayed across your LCD.
python3 ~/Adafruit_Python_CharLCD/examples/char_lcd.pyBuilding the RFID RC522 Reader Circuit1. Now that you have set up the 16×2 LCD Display we will now move onto adding the RFID reader into this circuit.For this section on wiring the RFID RC522 to the circuit, you will require the following pieces of equipment ready.
- 1 piece of Male to Male Breadboard Wire
- 6 pieces of Male to Female Breadboard Wire
- RFID RC522 Read/Writer
- Once you have everything that you need for the RFID circuit we can then proceed on to wiring everything up, this will be slightly more complicated thanks to the LCD circuit being already set up.
- Please note that this circuit diagram is assuming that you have followed the steps in the previous section for the LCD Display. If you are not utilizing the LCD, make sure you connect Physical Pin 6 on the Raspberry Pi to the ground rail on the breadboard.
- Follow the diagrams and steps below to wire the RFID circuit up to the Raspberry Pi.
- SDA connects to GPIO8 (Physical Pin 24)
- SCK connects to GPIO11 (Physical Pin 23)
- MOSI connects to GPIO10 (Physical Pin 19)
- MISO connects to GPIO9 (Physical Pin 21)
- GND connects to Breadboard Ground Rail.
- RST connects to GPIO25 (Physical Pin 22)
- 3.3v connects to 3v3 (Physical Pin 1)
- Enabling the SPI interface1. With the RFID now wired to our Raspberry Pi, we will need to go into the raspi-configtool to enable the SPI interface. This interface is required so that we can communicate with the RC522 module.To do this, you need to first launch the raspi-config tool by running the following command.
- 2. Upon running the command, you will see with a screen showing various options that you can configure.For now, we are only interested in activating the SPI interface. If you want to learn more, you can check out our ultimate guide to the Raspi-Config tool.On this screen use your arrow keys to go down and select “5 Interfacing Options” and press ENTER.
- 3. On the next screen, you will want to use your arrow keys to select the “P4 SPI” option, once selected press ENTER
- 4. You will now need to confirm if you want to enable the SPI Interface. To this, you will want to use your arrow keys to select “Yes” and then press ENTER once it’s selected.
- 5. The SPI Interface should now be successfully enabled, and you should now see the text “The SPI interface is enabled” appear on the screen.Now before the SPI interface is fully enabled, we will need to restart the Raspberry Pi. We can achieve this by going back to the terminal by pressing ENTER and then ESC.Enter the following command to restart the Raspberry Pi.
- 6. Once the Raspberry Pi has finished rebooting, you can verify that the SPI interface has been enabled by running the following command.This command will retrieve the list of enabled kernel modules and grab anything from that list that contains the text “spi“.
lsmod | grep spiIf you see the text “spi_bcm2835” appear in the command line, then you are now ready to proceed to test that the circuit is working correctly. Once that is done we can set up our RFID powered attendance system.If it doesn’t appear, then we recommend you check out our guide on setting up the RFID RC522 for other methods of enabling the correct kernel module. Testing the RFID RC5221.
- Let’s now install the spidev library to our Raspberry Pi by using the following “pip” command.We rely on the spidev library to interact with the RFID reader interface.
sudo pip3 install spidev
- 2. Now that we have installed the spidev library to our Raspberry Pi we need to proceed to download the MFRC522 library by using the “pip” command.This library is what will handle the grunt work for our RFID attendance system.
sudo pip3 install mfrc522
- 3. Now that we have both the MFRC522 library and the spidev library installed to our Raspberry Pi let’s go ahead and make a directory to keep our test script.
- 4. Now we will need to write a short script to test that our RC522 is, in fact, able to read RFID cards and that everything is wired correctly.First, let’s open up our new script by running the following command, this will create a file called “read.py” in our recently created directory.
- 5. Enter the following lines of code into this file. If you want an explanation of everything here, then we recommend checking out our full guide on the RFID RC522.
#!/usr/bin/env python import RPi.GPIO as GPIO from mfrc522 import SimpleMFRC522 reader = SimpleMFRC522() try: id, text = reader.read() print(id) print(text) finally: GPIO.cleanup()Once done, save the file by pressing CTRL + X then Y and ENTER.
- 6. Now test the RFID RC522 by running the following script and tapping your RFID chip on the reader.
python3 ~/pi-rfid/read.pyThe Full Raspberry Pi RFID Attendance System Circuit1. With both circuits now setup, double check that everything is working correctly. Test by running the test scripts that we quickly put together in a previous couple of sections.
- If you are having issues, you can compare your final circuit to the diagrams below. These diagrams are designed to give you an idea of how the final circuit should look.
- Preparing the RFID Attendance System Database1. Now before we go ahead and program our RFID attendance system, we must first prepare and set up the MYSQL database. This database is where we will be keeping track of each RFID cards attendance and who owns that RFID card.You can delve into setting up MYSQL a bit deeper by following our MySQL tutorial and PHPMyAdmin guide. Our RFID Attendance system will walk you through most of the basics but the extra guide will teach you how to setup useful tools like PHPMyAdmin.Begin by installing MYSQL to your Raspberry Pi by running the following command on your Pi
sudo apt-get install mysql-server -y2. Next, we will need to run the “secure installation” script that comes packaged with MYSQL. This script will run you through some processes on making your MYSQL server more secure.Run this script by running the following command within the terminal on the Raspberry Pi.
sudo mysql_secure_installationWhen prompted make sure that you set a new password for the root MYSQL server. Additionally, you should answer “y” to most prompts such as disabling root login access to your MYSQL server.
- 3. Now let’s load up into the MYSQL command-line tool by running the following command. You will be prompted to enter the password you set in the previous step.As MariaDB when installed utilizes UNIX_SOCKET as the authentication method by default, we are required to log in using the superuser, do this by using sudo.
sudo mysql -u root -p
- 4. Let’s begin by creating a database where we will be storing all of the data that we will be utilizing for our RFID attendance system.We will be naming this database, “attendancesystem“. To create this database, run the following command.
CREATE DATABASE attendancesystem;
- 5. With our database created, let’s now create a user called “attendanceadmin” we will utilize this user in our Python scripts to read from our newly created database.Make sure you set the password for this to something unique and hard to guess. For our example, we will be just using “pimylifeup” as the password.
CREATE USER 'attendanceadmin'@'localhost' IDENTIFIED BY 'pimylifeup';
- 6. Now that we have created our user we need to give it the rights to access our “attendancesystem” database.We can do this by running the following command. This command will give our “attendanceadmin” user full privileges on any table within our database.
GRANT ALL PRIVILEGES ON attendancesystem.* TO 'attendanceadmin'@'localhost';
- 7. Before we create our tables, we need to utilize the “use” command so that we are directly interacting with the “attendancesystem” database.Begin interacting with the database by running the following command.
- 8. Now that we are dealing directly with the database that we want to utilize we can now start creating the tables where all our data will be stored.Running the following two commands will create the tables that we will rely on for storing data. We will explain the fields in these tables after we have created them.
create table attendance( id INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, user_id INT UNSIGNED NOT NULL, clock_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY ( id ) ); create table users( id INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, rfid_uid VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY ( id ) );
- You can leave the MYSQL tool by entering exit;Now that we have created the tables let’s take a look at the data we will be storing and how we will be using it in our script.For the attendance table, we are holding three pieces of data for each recorded RFID tap.
- id – This is an integer that is used to keep track of the current row and increases automatically.
- user_id – This is an integer, and we utilize this to tie attendance with a user in our users table that has the same id.
- clock_in – This variable stores a SQL timestamp. This timestamp is used to track when the user taps their RFID card onto the RFID reader.For the users table, we are holding four pieces of data for each user that we add.
- id – This is an integer that is used to keep track of the current user and increases automatically.
- rfid_uid – This variable is used to store the UID that is captured when an RFID card is tapped on the RFID reader.
- name – This variable stores the name of the person who owns the RFID card.
- created – We use this variable to keep track of when the user was created.
- Recording a User in the Attendance System
- 1. Before we get writing our attendance system scripts, we need first to install the Python “MYSQL Connector” using pip.Install the connector library by running the following command on your Pi.
sudo pip3 install mysql-connector-python
- 2. Let’s now create a folder to keep everything for this project.
- 3. Time to start writing our first Python script for our attendance system. This first script will allow you to create a user based on a tapped RFID card.Upon tapping the RFID card, the Python script will ask you to enter a username to register this card to a person.Start writing the first part of our attendance system by running the following command.
- 4. Into this new file write the following lines of code. We will explain what each section of code does as we go and why we are utilizing that code.
#!/usr/bin/env pythonWe add this line so that the operating system knows that this file should execute using Python.
import timeWe import the time library so that we can put the script to sleep, so things don’t occur instantly.
import RPi.GPIO as GPIOWe require the GPIO library so that we can run the cleanup function when the script ends.
from mfrc522 import SimpleMFRC522The SimpleMFRC522 library is used to make it easy to talk with our RFID reader.
import mysql.connectorWe utilize the MySQL connector so that we can talk with the database that we set up earlier.
import Adafruit_CharLCD as LCDFinally, we load in the Adafruit library for talking with LCDs. This library simplifies the process of communicating with our 16×2 display significantly.
db = mysql.connector.connect( host="localhost", user="attendanceadmin", passwd="pimylifeup", database="attendancesystem" )
- In this section of the code, we create our connection to our MYSQL server. For this function, we pass in all the information required to make the connection such as the host, user, database name and the password.The object created by the connector is stored in the db variable so that we can interact with the database easily.Make sure when entering this code that you replace the password with the one you set earlier in this guide for the “attendanceadmin” SQL user.
cursor = db.cursor()Here we instantiate a copy of the cursor object from our database connection. We utilize this object to interact with the database and to execute SQL queries.
reader = SimpleMFRC522()Now we prepare the SimpleMFRC522 library by instantiating it to our reader object. This library will allow us to easily talk with the RC522 later in the script to read input from the reader.
lcd = LCD.Adafruit_CharLCD(4, 24, 23, 17, 18, 22, 16, 2, 4);
- Our final setup line, this line prepares the CharLCD library for dealing with out 16×2 display. For this function, we pass in all the required pin numbers, amount of rows and more.
try: while True: lcd.clear() lcd.message('Place Card to\nregister') id, text = reader.read()
- This block of code is the start of our user creation logic. We will be wrapping the entirety of our logic first in a try: statement, we will explain why later on in this guide.We also wrap our logic in a while True loop. This loop will ensure that the code below will run indefinitely so that the end user can register multiple users in succession.
- Next, we clear the LCD on every loop to ensure we are dealing with a clean display before writing “Place card to register” to the screen. This text prompts the user to place their RFID card onto the reader.Finally, we utilize our SimpleMFRC522 library to read input in from our reader. This function will wait until a user places their RFID reader before it returns both the id of the card and the text stored on it.
cursor.execute("SELECT id FROM users WHERE rfid_uid="+str(id)) cursor.fetchone()
- In this section, we use the cursor to execute our first bit of SQL. In this SQL statement we are simply searching our “users” table to see if any rows have a matching RFID UID to the ID we retrieved when reading the RFID card.To grab the data that we retrieved we utilize another function from the cursor object, specifically the fetchone() function. This function will grab one row from the returned results.
if cursor.rowcount >= 1: lcd.clear() lcd.message("Overwrite\nexisting user?") overwrite = input("Overwite (Y/N)? ") if overwrite == 'Y' or overwrite == 'y': lcd.clear() lcd.message("Overwriting user.") time.sleep(1) sql_insert = "UPDATE users SET name = %s WHERE rfid_uid=%s" else: continue; else: sql_insert = "INSERT INTO users (name, rfid_uid) VALUES (%s, %s)"
- We start in this section by checking how many rows were returned by our last SQL call.If the SQL call returns any rows, we need to prompt the user whether they want to overwrite the already existing user.Inside the if statement we proceed to clear the LCD screen and display the message “Overwrite existing user?” and provide a prompt in the command line for the user to respond either Y to overwrite or anything else to cancel.Once the input function has received the input, we then check to see if the first character of the returned data is equal to ‘Y‘ or ‘y‘
- .If the first character does equal what we expect we then clear the LCD again. Next we display a message “Overwriting user” for one second.
- Lastly, we build the SQL query to update the existing entry with the new name that we specify in the next step. We do this process instead of deleting the old entry and re-adding it.If the user responds anything but ‘Y‘ and ‘y‘ to the input function we then skip back to the start of the loop by using “continue“.If this was not a duplicate entry, we build a different SQL query to create a new entry in our “users” table. This new entry will contain the new name that we specify in the next block of code and the RFID ID that we obtained when the user tapped their card
lcd.clear() lcd.message('Enter new name') new_name = input("Name: ") cursor.execute(sql_insert, (new_name, id)) db.commit() lcd.clear() lcd.message("User " + new_name + "\nSaved") time.sleep(2) finally: GPIO.cleanup()
- Our final segment of code is quite simple and wraps everything up. We start by clearing the LCD again and prompting the user on the LCD that they need to enter a new name.Meanwhile on the console, the text “Name: ” should appear as we utilize input to await the user’s input.Once a user has input a name into the console and pressed enter we then proceed to utilize the cursor object to execute the query that we formed in the previous section of code.We also create a tuple that’s passed into the execute function. This tuple contains the new name and the RFID card’s id. Both these values will automatically pass into our query strings on execution.Finally, we commit the changes to the database by calling the db object with the .commit() function. If we don’t call this function, our INSERT and UPDATE queries will not occur.We end our main code logic by clearing the LCD again and displaying a message that the new user has saved. We run a quick 2-second sleep to give the user enough time to see the message before we restart the loop.Lastly, we have our finally: statement, this is the other part of our try: statement. This bit of code ensures that no matter what happens we will run the GPIO.cleanupfunction.
- For example, if we press CTRL + Cwhile the script is running, it should still clean up the GPIO status.6. Hopefully, at this point, you will have finished writing the script into the file.However, if you would like to check over and ensure that everything is correct, then you can find the full version of the code below.Once you are happy with everything, save the file by pressing CTRL + X then Y and finally ENTER.
#!/usr/bin/env python import time import RPi.GPIO as GPIO from mfrc522 import SimpleMFRC522 import mysql.connector import Adafruit_CharLCD as LCD db = mysql.connector.connect( host="localhost", user="attendanceadmin", passwd="pimylifeup", database="attendancesystem" ) cursor = db.cursor() reader = SimpleMFRC522() lcd = LCD.Adafruit_CharLCD(4, 24, 23, 17, 18, 22, 16, 2, 4); try: while True: lcd.clear() lcd.message('Place Card to\nregister') id, text = reader.read() cursor.execute("SELECT id FROM users WHERE rfid_uid="+str(id)) cursor.fetchone() if cursor.rowcount >= 1: lcd.clear() lcd.message("Overwrite\nexisting user?") overwrite = input("Overwite (Y/N)? ") if overwrite == 'Y' or overwrite == 'y': lcd.clear() lcd.message("Overwriting user.") time.sleep(1) sql_insert = "UPDATE users SET name = %s WHERE rfid_uid=%s" else: continue; else: sql_insert = "INSERT INTO users (name, rfid_uid) VALUES (%s, %s)" lcd.clear() lcd.message('Enter new name') new_name = input("Name: ") cursor.execute(sql_insert, (new_name, id)) db.commit() lcd.clear() lcd.message("User " + new_name + "\nSaved") time.sleep(2) finally: GPIO.cleanup()
- 7. With our save_user script saved let’s go ahead and take it for a whirl to ensure that everything is operating as it should be and there are no mistakes from copying the code.Run the script by running the following command.
- 8. Tap your RFID card and see if everything is working as intended if it’s not double check your code and wiring. If you see “User Saved” then everything should be working.
Image Credit- Source
Content Credit – Source