首页 > 解决方案 > Python pyserial 一写延迟

问题描述

我有一个奇怪的问题pyserial,使用 Python 3.6.9,在 WSL Ubuntu 18.4.2 LTS 下运行

我设置了一个简单的函数来将 GCODE 命令发送到串行端口:

def gcode_send(data):
    print("Sending: " + data.strip())
    data = data.strip() + "\n"  # Strip all EOL characters for consistency
    s.write(data.encode())  # Send g-code block to grbl

    grbl_out = s.readline().decode().strip()
    print(grbl_out)

它有点工作,但我发送的每个命令都被“保留”,直到发送下一个命令。

例如

  1. 我发送G0 X0> 设备没有反应
  2. 我发送G0 X1> 设备对G0 X0
  3. 我发送G1 X0> 设备对G0 X1
  4. 等等...

我的设置代码是:

s = serial.Serial(com, 115200)

s.write("\r\n\r\n".encode())  # Wake up grbl
time.sleep(2)  # Wait for grbl to initialize
s.flushInput()  # Flush startup text in serial input

我现在可以解决延迟问题,但这很烦人,我找不到其他人遇到同样的情况。知道是什么原因造成的吗?

标签: pythonpyserial

解决方案


就这样吧。评论中承诺的代码。它的大部分被删除并进行了错误检查。

它是一款通过蓝牙在诺基亚Symbian系列智能手机上使用PyS60 Python控制台的打字终端。效果非常好。


from serial import *
from thread import start_new_thread as thread
from time import sleep
import sys, os

# Original code works on Linux too
# The following code for gettin one character from stdin without echoing it on terminal
# has its Linux complement using tricks from Python's stdlib getpass.py module
# I.e. put the terminal in non-blocking mode, turn off echoing and use sys.stdin.read(1)
# Here is Win code only (for brevity):
import msvcrt

def getchar ():
    return msvcrt.getch()

def pause ():
    raw_input("\nPress enter to continue . . .")

port = raw_input("Portname: ")
if os.name=="nt":
    nport = ""
    for x in port:
        if x.isdigit(): nport += x
    port = int(nport)-1

try:
    s = Serial(port, 9600)
except:
    print >> sys.stderr, "Cannot open the port!\nThe program will be closed."
    pause()
    sys.exit(1)

print "Port ready!"
running = 1

def reader():
    while running:
        try:
            msg = s.read()
            # If timeout is set
            while msg=="":
                msg = s.read()
            sys.stdout.write(msg)
        except: sleep(0.001)

thread(reader,())

while 1:
    try: c = getchar()
    except Exception, e:
        running = 0
        print >> sys.stderr, e
        s.write('\r\n\x04')
        break
    if c=='\003' or c=='\x04':
        running = 0
        s.write('\r\n\x04')
        break
    s.write(c)

s.close()
pause()


推荐阅读