Поиск определенного слова в последовательном выводе в функции while

#regex #while-loop #serial-port #rfid

#регулярное выражение #цикл while #последовательный порт #rfid

Вопрос:

В настоящее время я пытаюсь получить конкретную фразу из моего последовательного вывода Arduino Uno (с картой RFID-RC522) на python, но у меня возникают проблемы при попытке найти слово 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
 

(извините за мой беспорядочный код, я довольно новичок во всем этом)

Мой вывод:

 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);
  }
} 
 

Заранее спасибо за помощь!

Комментарии:

1. Вы скрываете любые потенциальные проблемы, помещая a try: except: вокруг теста. Это плохая практика для except абсолютно всех исключений. Удалите это, и если вы получите какое-то конкретное исключение, которое вам действительно нужно игнорировать, добавьте его явно как except TheExceptionYouSaw:… .

2. Спасибо! Теперь я получаю Type Error: a bytes-like object is required, not 'str' за if auth in data:

3. Неважно, я изменил значение «если» на «если if b'Authorised' in data: «. Спасибо за вашу помощь!

Ответ №1:

Как указал meuh, это try: except: улавливание ваших ошибок и их скрытие. «Авторизованный» должен быть преобразован в байтовый объект, чтобы сравнить данные.