Python3 双向串行通信:读入数据 [英] Python3 Two-Way Serial Communication: Reading In Data

查看:94
本文介绍了Python3 双向串行通信:读入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Python3 建立双向通信.有一个激光测距仪插入我的一个 USB 端口,我想向它发送/接收命令.我有一张可以发送的命令以及它们会返回什么,所以这部分已经存在了.

I am trying to establish a two-way communication via Python3. There is a laser range finder plugged into one of my USB ports and I'd like to send/receive commands to that. I have a sheet of commands which can be sent and what they would return, so this part is already there.

我需要的是一种实时进行的便捷方式.到目前为止,我有以下代码:

What I need is a convenient way to do it in real-time. So far I have the following code:

import serial, time

SERIALPORT = "/dev/ttyUSB0"
BAUDRATE = 115200

ser = serial.Serial(SERIALPORT, BAUDRATE)
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = None          #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
ser.writeTimeout = 0     #timeout for write

print ("Starting Up Serial Monitor")

try:
    ser.open()
except Exception as e:
    print ("Exception: Opening serial port: " + str(e))

if ser.isOpen():
    try:
        ser.flushInput()
        ser.flushOutput()
        ser.write("1\r\n".encode('ascii'))
        print("write data: 1")
        time.sleep(0.5)
        numberOfLine = 0
        while True:
            response = ser.readline().decode('ascii')
            print("read data: " + response)
            numberOfLine = numberOfLine + 1
            if (numberOfLine >= 5):
                break
        ser.close()
    except Exception as e:
        print ("Error communicating...: " + str(e))
else:
    print ("Cannot open serial port.")

所以在上面的代码中,我发送了1",它应该触发激光探测器的getDistance()"函数并返回以毫米为单位的距离.我在 Putty 上试过这个,它可以工作,返回最多 4 位数字的距离.但是,当我启动上面的 Python 脚本时,我的输出只有以下内容:

So in the above code I am sending "1" which should trigger "getDistance()" function of the laser finder and return the distance in mm. I tried this on Putty and it works, returns distances up to 4 digits. However, when I launch the above Python script, my output is only the following:

Starting Up Serial Monitor
Exception: Opening serial port: Port is already open.
write data: 1
read data: 

它永远存在.没有读取数据或任何内容.

and it goes forever. There is no read data or whatsoever.

我哪里弄错了?

推荐答案

显然更简单的代码版本解决了这个问题.

Apparently much more simpler version of the code solved the issue.

import serial
import time

ser = serial.Serial('/dev/ttyUSB0', 115200, timeout = 1) # ttyACM1 for Arduino board

readOut = 0   #chars waiting from laser range finder

print ("Starting up")
connected = False
commandToSend = 1 # get the distance in mm

while True:
    print ("Writing: ",  commandToSend)
    ser.write(str(commandToSend).encode())
    time.sleep(1)
    while True:
        try:
            print ("Attempt to Read")
            readOut = ser.readline().decode('ascii')
            time.sleep(1)
            print ("Reading: ", readOut) 
            break
        except:
            pass
    print ("Restart")
    ser.flush() #flush the buffer

根据需要输出:

Writing:  1
Attempt to Read
Reading: 20
Restart
Writing:  1
Attempt to Read
Reading:  22
Restart
Writing:  1
Attempt to Read
Reading:  24
Restart
Writing:  1
Attempt to Read
Reading:  22
Restart
Writing:  1
Attempt to Read
Reading:  26
Restart
Writing:  1
Attempt to Read
Reading:  35
Restart
Writing:  1
Attempt to Read
Reading:  36

这篇关于Python3 双向串行通信:读入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆