Introduction: Raspberry Pi RFID Triggered Email
I've never worked with an RFID reader before so had no idea how this was going to go. As usual though, someone else had done it and so the individual elements were easy enough - getting it all to work together was a bit of a struggle but it's been a great learning experience for me!
This project is can become a part of someone else's work. What I've done is gotten an RFID reader to scan an RFID card, then trigger the Pi camera to take an image and finally email that image.
It could form part of a wider access set up to open a lock or something. I haven't gone that far as I've no real need to - I just wanted to figure out how to do something with the few bits I had on hand at the time!
Step 1: Here's the Bits You'll Need for the Project....
Parallax RFID reader - I'm sure there is code out there for others. Or indeed the code below might work for a different one. I can't tell you that as this is the first time I've tried anything with them! I understand these are available with and without an FTDI chip. This one has it's own on board and from working with other things that require an FTDI cable, it's always seemed simpler to me to buy the components that have the FTDI chip on board.
RFID card - which comes with the reader.
Raspberry Pi - I have no doubt that this will work with pretty much any RPi - mine is an RPi 2 model B.
SD Card with Raspbian installed.
Raspberry Pi camera module.
Usb mini cable - for the RFID reader.
Step 2: Preparation...
If you've used the RPi camera module before you've most likely enabled it. If not, Open a terminal and type:
and move down to "Enable Camera". When prompted, select "YES" to enable the camera module. This will take you back to the raspi-config menu at which you can use the TAB key to go to "FINISH".
The RPi will ask if you want to reboot now - select NO. This is because we need to connect everything up now before restarting and so we need to shut down instead. To shutdown type the following into the terminal:
sudo shutdown -h now
Once shutdown you can connect the RFID scanner by USB to the Raspberry Pi. Also connect the RPi camera module. Now you can boot the Pi up again.
For the RPi to communicate with the RFID reader you'll need to install a few bits.
Open up the terminal on your RPi & at the $ prompt:
sudo pip install pyserial
Then "Enter" - if you get asked to confirm, just select "Y".
You'll also need to install this:
sudo apt-get install sqlite3
Once both of these are installed you're ready to create your python files to handle the jobs.
Step 3: The Code for Sending Email With Attachment...
I like to create a specific folder to separate projects. To create a folder type into the terminal:
Then to move to that folder and create your python files:
Note: You'll be creating 2 different python files. They kind of depend on each other to some extent so there's not much point in running one untill they are both created. Let's first create the 2 files and then go over what they're doing.
You're in the folder you created you can create the files:
sudo nano rf-img-mail.py
Now copy and paste the following code into terminal (I've highlighted bits you need to or can change):
import smtplib from email.MIMEMultipart
import MIMEMultipart from email.MIMEBase
import MIMEBase from email.MIMEText
import MIMEText from email.Utils
import COMMASPACE, formatdate from email
USERNAME = "YOURUSERNAME" # you'll need your own gmail username in here
PASSWORD = "YOURPASSWORD" #you'll need your gmail password here
def sendMail(to, subject, text, files=):
msg = MIMEMultipart()
msg['From'] = USERNAME
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
part.add_header('Content-Disposition', 'attachment; filename="%s"'
server = smtplib.SMTP('smtp.gmail.com:587') #this is for communicating through gmail. I've no idea about other mail handlers!
server.sendmail(USERNAME, to, msg.as_string())
sendMail( ["YOUR.EMAIL@gmail.com"], #change to match the receiver's email address
"RFID Access Notification", #Your subject line which can suit your project
"Someome has accessed your RFID lock, picture attached", #The body text of the email
["/home/pi/rf-parallax/rfid.jpg"] ) #the location of the image that will be taken - you'll need to change this to suit the directory name you've created.
Once you've copied and edited the necessary bits above, press CTRL + X and answer Y then ENTER a couple of times to save the file.
CREDIT where it's due: This is code from https://harizanov.com/2013/07/raspberry-pi-emalsms-doorbell-notifier-picture-of-the-person-ringing-it/ where it's triggered instead by a doorbell.
Step 4: Creating the RFID Reading Trigger File...
This file will be the one we actually run. It will listen for a card to be presented to the RFID reader then trigger the camera. Once the image is taken it will then call the previous python file to send the image as an attachment to your email.
sudo nano rf-read.py
And copy in the following contents:
# open sqlite database file db = sqlite3.connect('tagreads.db') cursor = db.cursor()
# check that the correct tables exists in database; create them if they do not
tables = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND (name='tagreads');").fetchall()
if len(tables) == 0 :
cursor.execute("CREATE table tagreads (timestamp, tagid)")
# connect to serial port on which the RFID reader is attached
port = serial.Serial('/dev/ttyUSB0', 2400, timeout=1)
lastid = ""
print("Present RFID tag")
# attempt to read in a tag
tagid = port.read(12)
# if tag read success full, save it to database and wait half a second;
# else try again
if(len(tagid) != 0) and (len(lastid) == 0):
# close and open the port to blink the light and give visual feedback
# take an image on presentation of rfid tag
print("Taking RFID image - remain still while camera led is on")
os.system("raspistill -w 640 -h 480 -o rfid.jpg") #this is a REALLY handy feature in Python. No matter what you want to run you can place commands between the quotes in the same way you can run things from the command line. So for taking a picture like here, you can add in all the options available to raspistill.
tagid = tagid.strip()
timestamp = time.time()
cursor.execute("INSERT INTO tagreads VALUES (?,?);", (timestamp, tagid))
print("Time:%s, Tag:%s" % (timestamp,tagid))
# The actual mail send is completed in a seperate python script located within the same folder
os.system("python rf-img-mail.py") #Again, using that
print("Present RFID tag")
lastid = tagid
print ("Program interrupted")
Again once you've copied and edited the necessary bits above, press CTRL + X
and answer Y then ENTER a couple of times to save the file.
CREDIT where's its due: I got the vast majority of this code from here - http://theatticlight.net/posts/Using-a-Parallax-RFID-reader-on-the-Raspberry-PI/
Step 5: Running It All Together....
Here's your moment of truth - and if you've gotten your email details correct then I'd expect this should work for you straight away.
Any time you want to run this, just open a terminal and navigate to the location of the 2 python files.
One image is an example of how it should all react on starting and when presenting the RFID card. It won't look the same as yours as I'm using my Ubuntu laptop to ssh to the RPi. I've also got a different filename - which is pretty much irrelevant!
The other image is the email that the recipient will get.