gpt4 book ai didi

python - PySerial:read() 和 readinto() 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 19:02:26 28 4
gpt4 key购买 nike

我一直在我的代码中使用 pySerial 3.4 从串行端口(准确地说是 RFID 芯片读取器/写入器)提取数据。我需要向阅读器发送命令,然后从阅读器读取结果。


基本上,我正在编写一个 12 字节的命令,然后尝试接收 24 字节的输出。我的问题是:为什么 port.read(24) 不能工作,但 res = bytearray(24); port.readinto(res);工作成功了吗?附上完整代码:

import serial

ser = serial.Serial('COM5',9600,timeout=5,rtscts=True,inter_byte_timeout=5)

def compose_find(port):
port.write(bytes.fromhex('555500000003020405'))
port.flush()
return port.read(12)[6] == 0

def compose_read(port,sec_loc=0,block_loc=0,key='F'*12):
assert sec_loc in range(0,16),'sector location is from 0~15'
assert block_loc in range(0,4),'block location is from 0~3'
assert compose_find(port),'cannot read card!'

sec_loc = '0'+str(hex(sec_loc))[2:]
block_loc = '0'+str(hex(block_loc))[2:]
command = '55 55 00 00 00 0E 03 07 00 00 {} {} 60
{}'.format(sec_loc,block_loc,key).replace(' ','')
parity = str(hex(reduce(lambda x,y:x^y,bytes.fromhex(command))))[2:]
if len(parity) == 1: parity = '0'+parity
command += parity
print(command)
port.write(bytes.fromhex(command))
port.flush()
res = bytearray(24)
port.readinto(res)
return res

compose_read(port=ser,sec_loc=8,block_loc=2)

最佳答案

readinto(buf) 最多读取 len(buf) 字节并返回,而 read(num)阻塞 直到收到 num 个字节。如果您希望 read() 在没有足够数据可用的情况下返回,您必须在打开端口时指定 timeout

关于python - PySerial:read() 和 readinto() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51165158/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com