简体   繁体   中英

How to read from multiple serial inputs in Python?

I'm trying to read two serial ports for an access control script in Python. One serial port has an RFID reader, the other has a barcode reader. I want the user to present his card, whether it is barcode or RFID, and the script to validate the access permission.

serRFID = serial.Serial(
  port = '/dev/ttyUSB0',
  baudrate = 9600,
  parity = serial.PARITY_NONE,
  stopbits = serial.STOPBITS_ONE,
  bytesize = serial.EIGHTBITS,
  timeout = 10)

serBARC = serial.Serial(
  port = '/dev/ttyACM0',
  baudrate = 38400,
  parity = serial.PARITY_NONE,
  stopbits = serial.STOPBITS_ONE,
  bytesize = serial.EIGHTBITS,
  timeout = None)

def readtag():
  global tag_inp
  serBARC.reset_input_buffer()
  tag_inp = ""
  while tag_inp == "":
    read_byte1 = serBARC.read(11)
    if len(read_byte1) == 11:
      tag_inp = read_byte1

Above works, but obviously only with the barcode reader. If I change to serRFID instead of serBARC in the "readtag" definition, it also works but I want both to be read, and only the one that returns data (RFID or Barcode) to be stored as "tag_inp"

read_byte1 = serBARC.read(11)

This is a blocking call and will wait indefinitely until 11 bites are read from the port. What you can do instead is add a timeout, and then do the same with the other port:

read_byte1 = serBARC.read(11, timeout=5) # 5 seconds, tweak the timeout as per your liking
read_byte2 = serRFID.read(11, timeout=5)

Alternatively, you can specify timeouts when creating both the Serial objects, as you have done already for the RFID port. Then you can call read on both of them in the loop as I've shown above, but without needing to specify timeouts.

You can then proceed to check which one of read_byte1 and read_byte2 has the required length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM