繁体   English   中英

如何从Python中的多个串行输入读取?

[英]How to read from multiple serial inputs in Python?

我正在尝试为Python中的访问控制脚本读取两个串行端口。 一个串行端口具有RFID读取器,另一个串行端口具有条形码读取器。 我希望用户出示其卡(无论是条形码还是RFID)以及用于验证访问权限的脚本。

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

上面的作品,但显然只有条形码阅读器。 如果在“ readtag”定义中更改为serRFID而不是serBARC,它也可以使用,但是我希望两者均能被读取,并且只有返回数据(RFID或条形码)的存储为“ tag_inp”

read_byte1 = serBARC.read(11)

这是一个阻塞的调用,它将无限期地等待,直到从端口读取11位为止。 您可以做的是添加一个超时,然后对另一个端口执行相同的操作:

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

另外,您可以在创建两个Serial对象时指定超时,就像已经为RFID端口所做的那样。 然后,您可以如上所示在循环中对它们两个都调用read,但是无需指定超时。

然后,您可以继续检查read_byte1read_byte2中的哪一个具有所需的长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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