首页 > 解决方案 > 在 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);
  }
} 

提前感谢您的帮助!

标签: regexwhile-loopserial-portrfid

解决方案


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


推荐阅读