USB RFID读写器 + 树莓派
我有一个USB RFID读卡器连接在树莓派上,这个读卡器是中国品牌的,它的工作方式像键盘一样,可以读取前10位数字。
我想做的就是从卡片上读取数据,然后和我代码中存储的数字进行比较。
#!/usr/bin/env python
import time
import sys
card = '0019171125' # Stored good card number consider using a list or a file.
def main(): # define a main function.
while True: # loop until the program encounters an error.
sys.stdin = open('/dev/tty0', 'r')
RFID_input = input()
if RFID_input == card: # coppare the stored number to the input and if True execute code.
print "Access Granted"
print "Read code from RFID reader:{0}".format(RFID_input)
else: # and if the condition is false excecute this code.
print "Access Denied"
tty.close()
main() # call the main function.
但是我总是看到这个错误信息:
RFID_input = input()
^ IndentationError: unindent does not match any outer indentation level
有什么建议吗?
2 个回答
1
这是正确缩进的代码:
#!/usr/bin/env python
import time
import sys
card = '0019171125' # Stored good card number consider using a list or a file.
def main(): # define a main function.
while True: # loop until the program encounters an error.
sys.stdin = open('/dev/tty0', 'r')
RFID_input = input()
if RFID_input == card: # compare the stored number to the input and if True execute code.
print "Access Granted"
print "Read code from RFID reader:{0}".format(RFID_input)
else: # and if the condition is false excecute this code.
print "Access Denied"
# where is tty defined??
tty.close()
if __name__ == '__main__':
main()
但是你仍然没有定义tty...
7
Python对代码的缩进很敏感,所以你需要正确地缩进你的代码:
#!/usr/bin/env python
import time
import sys
card = '0019171125'
def main():
while True:
sys.stdin = open('/dev/tty0', 'r')
RFID_input = input()
if RFID_input == card:
print "Access Granted"
print "Read code from RFID reader:{0}".format(RFID_input)
else:
print "Access Denied"
tty.close()
main()
注意,tty.close()
会报错,因为没有定义tty
。你可能想在这里关闭sys.stdin
,不过其实在可以直接从那个流读取的情况下,使用sys.stdin
来处理其他流并不是个好主意。
另外,不要用input()
来获取用户输入,应该使用raw_input
。
def main():
with open('/dev/tty0', 'r') as tty:
while True:
RFID_input = tty.readline()
if RFID_input == card:
print "Access Granted"
print "Read code from RFID reader:{0}".format(RFID_input)
else:
print "Access Denied"