在while函数的串行输出中搜索特定单词



我目前正试图从我的Arduino Uno(带有RFID-RC522卡)中获取python中的串行输出,但试图使用serial模块在输出中找到Authorised这个词时遇到问题

我已经尝试了许多不同的方法,如正则表达式和if语句,但我不能为我的生命得到它的break脚本一旦它发现了Authorised

下面是我的代码:
import serial
import time
import re
from re import search
device = 'COM5'     ## Serial Port for Arduino
print("Trying device on: " + device)
arduino = serial.Serial(device, 9600, timeout=1)    ## Try connecting to Serial Port from 'device'
try:
print("Connected to: " + arduino.portstr)
except:
print("Failed to connect to device on " + device)
auth = "Authorised"
while True:
# for c in arduino.read():
#     seq.append(chr(c)) #convert from ANSII
#     joined_seq = ''.join(str(v) for v in seq) #Make a string from array
#     if chr(c) == 'n':
#         print("Line " + str(count) + ': ' + joined_seq)
#         seq = []
#         count += 1
#         break
data = arduino.readline()
print(data) 
try:
if auth in data:
print("Done!")
break

# pieces = data.split(" ")
# test = pieces[0],pieces[1]
# data.find(auth) != -1

except:
pass

(请原谅我的代码混乱,我对这一切都很陌生)

我的输出是:
Trying device on: COM5
Connected to: COM5
b''
b'Place your card near reader...rn'
b'rn'
b''
b''
b' 06 3D 65 D9rn'
b'Authorisedrn'
b'rn'
b''
b''
b''
b''
b''
b''

我的Arduino代码是:

#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
void setup() 
{
Serial.begin(9600);   // Initiate a serial communication
SPI.begin();      // Initiate  SPI bus
mfrc522.PCD_Init();   // Initiate MFRC522
Serial.println("Place your card near reader...");
Serial.println();
}
void loop() 
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) 
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) 
{
return;
}
//Show UID on serial monitor
//Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) 
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
//Serial.print("Message : ");
content.toUpperCase();
if (content.substring(1) == "06 3D 65 D9") //change here the UID of the card/cards that you want to give access
{
Serial.println("Authorised");
Serial.println();
delay(1000);
}
else   {
Serial.println("Denied");
delay(1000);
}
} 

提前感谢您的帮助!

正如meuh指出的那样,try: except:正在捕捉您的错误并隐藏它们。为了比较数据,必须将' authorized '转换为字节对象。

相关内容

  • 没有找到相关文章

最新更新