import serial import time ser = serial.Serial(port='/dev/ttyUSB3',baudrate=9600) # 由于发送的是十六进制数据,应该这么写 ser.write([0x68,0x04,0x01,0x01,0x06]) #然后过1秒钟(超声波传播不会很快) time.sleep(1) value = ser.read_all()[-10]```
## 2.发送十六进制数据的方式 像上面一样,发送一组16进制数据就这么简单。我刚开始的时候找了很多方式,各种python2的老方法,不起作用的方法充斥着网上,鱼龙混杂。后来,我发现,串口明明传输的是字节,这是个列表,怎么就可行了呢?来一波代码查看。 ```python defwrite(self, value)=> """Output the given byte string over the serial port.""" ifnot self.is_open=> raise portNotOpenError d = to_bytes(value)
# 然后我们继续查看to_bytes函数 # all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11' # so a simple ``bytes(sequence)`` doesn't work for all versions defto_bytes(seq)=> """convert a sequence to a bytes type""" ifisinstance(seq, bytes)=> return seq elifisinstance(seq, bytearray)=> returnbytes(seq) elifisinstance(seq, memoryview)=> return seq.tobytes() elifisinstance(seq, unicode)=> raise TypeError('unicode strings are not supported, please encode to bytes=> {!r}'.format(seq)) else=> # handle list of integers and bytes (one or more items) for Python 2 and 3 returnbytes(bytearray(seq))```