A RFID-RC522 connected to Raspberry Pi and a python script which reads RFID tag and prints out the result of the reading. And the aim of the project is to transfer the ID of the RFID tag to a Microsoft SQL Server database on a remote PC as soon as the reader reads the ID. On the Microsoft SQL server database there is a table called Attendance where the ID to be stored in.

The recent problem is that when I run the below script and try to make a read for the card it says :

Traceback (most recent call last): File "rfidreader.py", line 102, in <module> 

"INSERT INTO Attendance VALUES ('"+str (uid) +"','"+str (cardtypename) +"')" 

NameError: name 'uid' is not defined

Please check the script and help me to solve the problem!

here's the script :

#!/usr/bin/env python
# -*- coding: utf8 -*-

import RPi.GPIO as GPIO
import MFRC522
import signal
import time
from os import getenv
import pymssql

server = getenv("PYMSSQL_TEST_SERVER")
user = getenv("PYMSSQL_TEST_USERNAME")
password = getenv("PYMSSQL_TEST_PASSWORD")    
conn = pymssql.connect("", "sa", "Tne-project2017", "project")

continue_reading = True
# the uid of the last recognized card
lastcarduid = None
# the time a card uid was last seen
lastcardtime = 0.0

# this long after a card has been noticed, it can be noticed again
# This works because the reader generates repeated notifications of the card
# as it is held agains the reader - faster than this interval.
# The timer is restarted every time the reader generates a uid.
# If you sometimes get repeated new card IDs when holding a card against the
# reader, increase this a little bit.

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

## Welcome message
#print "Welcome to the MFRC522 data read example"
#print "Press Ctrl-C to stop."

def gettypename( typecode ):
    typecode &= 0x7F;
    if typecode == 0x00:
        return "MIFARE Ultralight or Ultralight C"
    elif typecode == 0x01:
        return "MIFARE TNP3XXX"
    elif typecode == 0x04:
        return "SAK indicates UID is not complete"
    elif typecode == 0x08:
        return "MIFARE 1KB"
    elif typecode == 0x09:    
        return "MIFARE Mini, 320 bytes"
    elif typecode == 0x10 or typecode == 0x11:
        return "MIFARE Plus"
    elif typecode == 0x18:
        return "MIFARE 4KB"
    elif typecode == 0x20:
        return "PICC compliant with ISO/IEC 14443-4"
    elif typecode == 0x40:
        return "PICC compliant with ISO/IEC 18092 (NFC)"
    return "Unknown type";

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
    # Scan for cards    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # Get the UID of the card
    (status,rawuid) = MIFAREReader.MFRC522_Anticoll()

    # If we have a good read of the UID, process it
    if status == MIFAREReader.MI_OK:
        uid = "{0[0]:02x}{0[1]:02x}{0[2]:02x}{0[3]:02x}".format(rawuid)
#        # Print UID
#        print "Card read UID: "+uid
        newcard = False
        if lastcarduid:
            if lastcarduid != uid or (lastcardtime and time.clock() - lastcardtime >= CARDTIMEOUT):
                newcard = True
            newcard = True

        if newcard:
#            print "New Card read UID: "+uid
            # String payload = "{\"d\":{\"cardUID\":\"";
            #  payload += UID_HEX;
            #  payload += "\",\"cardtype\":\"";
            #  payload += mfrc522.PICC_GetTypeName(piccType);
            #  payload += "\"}}"; 
            rawcardtype = MIFAREReader.MFRC522_SelectTag(rawuid)
            cardtypename = gettypename( rawcardtype )
            print '{ "cardUID": "'+uid+'","cardtype":"'+cardtypename+'" }'
cursor = conn.cursor()
"INSERT INTO Attendance VALUES ('"+str (uid) +"','"+str (cardtypename) +"')"
# you must call commit() to persist your data if you don't set autocommit to True
# remember the last card uid recognized
lastcarduid = uid
# remember when it was seen
lastcardtime = time.clock()
  • You say "The recent problem is that when I run the below script and try to make a read for the card it says". Why don't you undo the change you made as that is what is presumably causing the problem? – joan Apr 8 '17 at 17:52
  • Dear Joan, the problem isn't about if the script run or not, the problem is that when I make a read for the card it says the "uid" is not defined. – Zaid Al Aqqad Apr 8 '17 at 18:17
  • The mysql insert statement is only called after the continue_reading loop completes at program termination. Are you sure you have the correct indentation? – joan Apr 8 '17 at 19:09
  • It's sql not mysql... Yes, sure ! – Zaid Al Aqqad Apr 9 '17 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.