如何将一系列串行数据连续发送到多个功能中,并在各处更新数据



我想编写一个脚本,它有几个不同的函数,其中必须接收一个充满串行数据的数组。串行数据每1秒来自一个arduino。(别担心。我使用随机数组将代码更改为可重复的示例。(

到目前为止,我所成功的是,代码确实第一次将数组发送到函数示例中一次,并按照我的意愿显示它

它还没有做到的是,函数内部的信息在从arduino传入时会得到更新。当你看到代码时,你会说,数据只发送一次。但是,当我在循环中每隔一秒对数组进行随机化时,循环显然会阻塞其余的代码,并且gui不会构建。事实是,串行读取在没有循环的情况下更新阵列,这是非常值得赞赏的。

问题是:如何将此更新传输到函数中。记住:对于下面的代码来说,简单地在函数中插入串行读取内容是一个自然的解决方案。但这只是将问题归结为问题的代码。真正的代码在几个函数中调用了几个小部件,我最终复制了-&amp-将整个串行数据信号调节代码块粘贴到每个需要数据的函数中。这大大增加了代码的滞后,因此没有解决方案。

示例脚本包含注释掉的部分,以便更容易理解我迄今为止试图解决的问题:

import numpy as np
#import rhinoscriptsyntax as rs
import time
import tkinter as tk
import serial
"""
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 500000,
#parity=serial.PARITY_NONE,
#stopbits=serial.STOPBITS_ONE,
#bytesize=serial.EIGHTBITS,
timeout=1
)
ser.flushInput()
ser.flushOutput()
#I've been trying to embed the serial read stuff inside a function itself, which I'd LOVE to implement,
#but it has the same problem: either it is called just once as it is written here, ore a loop blocks the code
def serial_data():
#serialData = ser.readline()
#serialData = serialData.decode()
#floats = [float(value) for value in serialData.split(',')]
#arr = np.array(floats)
arr = np.random.rand(100)
time.sleep(1)
return arr
"""
#above commented out and replaced with random array below. 
#serialData = ser.readline()
#serialData = serialData.decode()
#floats = [float(value) for value in serialData.split(',')]
#arr = np.array(floats)
arr = np.random.rand(100)
time.sleep(1)
print(np.round(arr, 3))
def nextWindow(root):
frame1 = tk.Frame(root, width=800, height=500)
frame1.pack()
text= tk.Text(frame1, width=80, height= 12, bd=0)
text.pack()
text.delete("1.0",tk.END)
#serialData = serial_data()
#text.insert(tk.INSERT, serialData)
text.insert(tk.INSERT, np.round(arr, 3))
text.update()
root = tk.Tk()
root.title('PythonGuides')
root.geometry('300x200')
root.config(bg='#4a7a8c')
nextWindow(root)
root.mainloop()

关于如何使用.after"循环";(代码注释中的解释(:

import tkinter as tk
# for the example
counter = 1

# your serial_data function, renamed to
# be more self-explanatory
def get_serial_data():
# put the serial reading stuff here
# the counter is just an example
global counter
counter += 1
return str(counter)

def update_text(txt):
# get data, clear text widget, insert new data
serial_data = get_serial_data()
txt.delete('0.0', 'end')
txt.insert('end', serial_data)
# schedule this function to run again in 100ms
# so it will repeat all of this effectively
# updating the text widget, you don't need to call `.update`
# note that this is not recursive
root.after(100, update_text)

def create_text():
text = tk.Text(root)
text.pack()
update_text(text)

root = tk.Tk()
create_text()
root.mainloop()

相关内容

  • 没有找到相关文章

最新更新