我是Python的新手,我试图在rasberry pi上构建一个Rfid读卡器。我使用python脚本读取卡片并获取卡片UID,然后处理其他功能等,但是在传递变量时我碰到了墙,
我的代码:
import RPi.GPIO as GPIO
import MFRC522
import signal
import time
import datetime
import socket
import run
device = (socket.gethostname()) # Define Device name
# Define logfile Long version |
logfile = "/home/piadmin/MFRC522-python/" + device + ".csv"
# logfile = device + ".csv"
continue_reading = True
# 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
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
# Welcome message
print "Waiting for card to read.."
print "Press Ctrl-C to stop."
# 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)
# If a card is found
if status == MIFAREReader.MI_OK:
print "Card detected"
# Get the UID of the card
status,uid = MIFAREReader.MFRC522_Anticoll()
print uid
time.sleep (1)
run.run()
在最后一行上面的代码中调用run.py WIP:
idlist = file('/home/piadmin/temp/idlist.txt') # known ID list
inlog = file('/home/piadmin/temp/in.txt') # IN log
status = 'None'
def checkid():
for line in idlist:
if uid in line:
return True
else:
return False
def checkin():
for line in inlog:
if uid in line:
return True
else:
return False
#uid = raw_input("Please enter uid: ")
#print "uid ->", uid
def run():
if checkid() == True:
print 'id = true'
if checkin() == True:
print 'in = true'
print 'set OUT'
status = 'OUT'
f = open('in.txt','r+')
d = f.read().splitlines()
f.seek(0)
for i in d:
if i != uid:
f.write(i)
f.write('\n')
f.truncate()
f.close()
return True
else:
print 'in = false, set IN'
status = 'IN'
f = open('in.txt','a')
f.write(str(uid))
f.write('\n')
f.flush()
f.close()
return True
else:
print 'check id not true, not checking more (finger)'
return False
一旦执行代码,我得到输出:
Waiting for card to read..
Press Ctrl-C to stop.
Card detected
[101, 116, 172, 79, 242]
Traceback (most recent call last):
File "read.py", line 49, in <module>
run.run()
File "/home/piadmin/work/run.py", line 26, in run
if checkid() == True:
File "/home/piadmin/work/run.py", line 11, in checkid
if uid in line:
NameError: global name 'uid' is not defined
我无法弄明白为什么&#34; NameError:全球名称&#39; uid&#39;没有定义&#34;发生以及如何正确传递在每个循环传递上分配的uid值。
答案 0 :(得分:0)
您在哪里定义变量uid? 如果全局变量&#34; uid&#34;在模块中定义, 您可以使用以下命令从其他模块访问:
theNameOfModuleWhichDefineUID.uid
修改强>
例如,如果全局变量&#34; uid&#34;在模块&#34; iammodule&#34;中定义 您可以使用此命令访问:
import iammodule
print(iammodule.uid)
或
from iammodule import *
print(uid)