0

我正在尝试读取串行端口的响应。(我正在使用 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))

起初我直接使用 print(response) 得到的是:

trying to read
�#��

因此我使用 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很陌生,不知道问题是什么。

4

1 回答 1

1

您的字符串已经是十六进制文字:

>>> x = '\x94#\xdb\xff'
>>> x.encode('hex')
'9423dbff'
>>> int(x.encode('hex'),16)
2485378047L
于 2012-06-19T14:09:19.633 回答