regex - 在 while 函数的串行输出中搜索特定单词
问题描述
我目前正在尝试从我的 Arduino Uno(使用 RFID-RC522 卡)中获取特定短语 python 中的串行输出,但在尝试Authorised
使用serial
模块在输出中查找单词时遇到问题
break
我尝试了许多不同的方法,例如正则表达式和 if 语句,但是一旦找到它,我就无法终生将它放到脚本中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...\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''
对于那些想知道的人,我的 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:
是捕捉你的错误并隐藏它们。'Authorised' 必须转换为字节对象才能比较数据。
推荐阅读
- php - 如何修复Android中的Paytm Session Expired失败错误?
- python-2.7 - lxml:编写增量漂亮的打印 xml
- python - 在所有带有文本的节点及其 xpath 之间创建映射
- python - 画布对象;在 Abaqus/CAE 中找到了 PartInstance,期待元组
- excel - 如何根据日期将一个值引用到各个单元格?
- reactjs - 为对象的一个属性设置默认道具
- javascript - 如何使用来自 magento 1.9 中自定义 javascript 文件的 ajax 调用发送产品详细信息?
- c# - 在 c# 中使用母版页自定义用户身份验证
- django - 根据字典键过滤模型
- php - 从移动应用程序检索 PHP 上的 json 数据