ValueError, Serial port response reading with python

2024-03-29 13:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试读取串行端口的响应。(我正在使用RFID模块)以下是我的代码:

import serial
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 9600
ser.timeout = 3
ser.open()
if ser.isOpen():
    ser.write("\xFF\x01\x03\x10\x02\x02\x18")
    print("command written")
while ser.isOpen():
    response = ser.read(5)
    print("trying to read")
    print(int(response,16))

起初,我使用直接打印(响应),得到的是:

^{pr2}$

因此,我使用print(int(response,16))将响应转换为整数,现在我得到了错误:

Traceback (most recent call last):
  File "serialread.py", line 13, in <module>
    print(int(response,16))
ValueError: invalid literal for int() with base 16: '\x94#\xdb\xff'

我该怎么办?我对python相当陌生,不知道问题会是什么。在


Tags: 模块端口代码importreadportresponseserial