python - 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)
它有点工作,但我发送的每个命令都被“保留”,直到发送下一个命令。
例如
- 我发送
G0 X0
> 设备没有反应 - 我发送
G0 X1
> 设备对G0 X0
- 我发送
G1 X0
> 设备对G0 X1
- 等等...
我的设置代码是:
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
我现在可以解决延迟问题,但这很烦人,我找不到其他人遇到同样的情况。知道是什么原因造成的吗?
解决方案
就这样吧。评论中承诺的代码。它的大部分被删除并进行了错误检查。
它是一款通过蓝牙在诺基亚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()
推荐阅读
- python - 如何在 django api 中发送图像?
- go - 如何使用命令行解压缩 Go compress/gzip 包生成的文件?
- scala - 如何使用 Traverse 运行效果列表
- c - 如何在 C 中跟踪并返回链表的头部,同时将节点添加到末尾
- react-native - 如何在反应导航 5.0 中访问传递给基于类的组件的参数?
- amazon-web-services - Cloudformation 中的跨账户安全组参考
- reactjs - Reactjs Facebook 登录
- django - 在 docker build 中运行“/usr/local/bin/gunicorn”会显示“stat /usr/local/bin/gunicorn:没有这样的文件或目录”
- r - 绘制二进制和连续值的热图
- javascript - 有没有可能使用javascript中的ISOtime格式找到时区的方法