如何解决串行通信中的这种绘图问题? [英] How to solve this plotting problem in serial communication?
问题描述
下面是简单的代码:
#import 序列号从 tkinter 导入 *从 matplotlib 导入 pyplot 作为 plt导入matplotlib.animation作为动画从matplotlib导入样式从matplotlib.backends.backend_tkagg导入FigureCanvasTkAgg导入序列无花果 = plt.gcf()图.show()fig.canvas.draw()ser = serial.Serial('COM35',115200,超时= .1)为真:数据= ser.readline()打印(数据)plt.plot(数据)fig.canvas.draw()
现在当我运行它时,我得到了这样的东西..in pic
并且数据值是这样的
但是我需要输出类似这样的东西(它是连续的图)..
但在将 list 关键字添加到 list(ser.readline())
后,我收到此错误..
此答案不如使用
您可以通过彩色线段看到哪些数据已添加在一起.
Here this simple code:
#import serial
from tkinter import *
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import serial
fig = plt.gcf()
fig.show()
fig.canvas.draw()
ser = serial.Serial('COM35', 115200, timeout=.1)
while True:
data = ser.readline()
print(data)
plt.plot(data)
fig.canvas.draw()
now when i run this i'm getting something like this..in pic
and the data values are like this
but i need output something like this (which is continuous graph)..
but after adding the list key word on to the list(ser.readline())
I get this error..
This answer is not as elegant as using the animation-api - but it works.
You have to adapt quite a lot - for sake of giving a Minimal, Complete, and Verifiable example I had to implement my own "serial" dataprovider:
from itertools import cycle
data = [0,0,0,0,0,0,0,0,0,2,25,64,92,119,132,139,124,123,103,71,38,3]
cyc = cycle(data)
def serial():
from random import randint
def create_data():
for k in range(randint(2,3)):
yield next(cyc)
return list(create_data())
One way to solve it:
You need to get the the axes of your plot as well to adjust the "area" that is shown, then you need to supply correct x-values as "time" and the y-values as reading from serial (you can increment a "how many data received" variable on each draw for the time):
from tkinter import *
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
ax.set_ylim(-200, 200)
ax.set_xlim(0,110)
fig.show()
fig.canvas.draw()
time = 0
last = 0
while True:
# "animate" x-axis
if time > 100:
ax.set_xlim(time-100,time+10)
data = serial()
print(data)
# add the last datapoint again so you get a continuous curve
plt.plot([time-1]+[time+x for x in range(len(data))], [last]+data)
# increment time
time += len(data)
# remember last data-value
last = data[-1]
fig.canvas.draw()
To get (text output omitted - it just repeats the data from above differently chunked):
You can see by the colored line-segments which data was added together.
这篇关于如何解决串行通信中的这种绘图问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!