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

问题描述

我目前正在尝试从我的 Arduino Uno(带有 RFID-RC522 卡)串行输出获取特定短语,但在尝试使用 Authorised 模块在输出中查找单词 serial 时遇到问题

我尝试了许多不同的方法,例如正则表达式和 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

对于那些想知道的人,我的 Arduino 代码是:

Trying device on: COM5
Connected to: COM5
b''
b'Place your card near reader...\r\n'
b'\r\n'
b''
b''
b' 06 3D 65 D9\r\n'
b'Authorised\r\n'
b'\r\n'
b''
b''
b''
b''
b''
b''

提前感谢您的帮助!

解决方法

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