如何打印串口收到的数据?

如何打印串口收到的数据?

在此输入图像描述下面是我写的Python代码:

import serial,time
#initialization and open the port
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 1152000
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_TWO #number of stop bits
    #ser.timeout = None          #block read
ser.timeout = 5               #non-block read
    #ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control

try: 
    ser.open()

except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():
    read_data = ser.read(10)
   # response  = ser.readline()
    print"Data received : " + read_data

else:
   print "Can not open serial port"

执行后,它显示接收到的数据太奇怪而无法读取。响应的屏幕截图已附在问题下方的上方。

答案1

请尝试以下操作:

sudo apt-get install python-serial

import serial

port = serial.Serial("/dev/ttyUSB0", baudrate=115200, timeout=3.0)

while True:
    port.write("\r\nSay something:")
    rcv = port.read(10)
    port.write("\r\nYou sent:" + repr(rcv))

相关内容