python打开串口时怎么设置停止位_在Python中绘制串行数据如何暂停matplotlib figure?...

因此,解决问题的一个好方法是使用线程运行绘图窗口,并通过主线程执行控制。可以这样实现:import serial

import numpy as np

from matplotlib import pyplot as plt

from threading import Thread,Event

import time

#A simple ring buffer to keep the plotting data in

class RingBuffer(object):

def __init__(self,size):

self.size = size

self._size = 2*size

self._buffer = np.zeros(self._size)

self._idx = 0

def insert(self,val):

idx = self._idx%self.size

self._buffer[idx] = val

self._buffer[idx+self.size] = val

self._idx+=1

if self._idx > self.size:

self._idx-=self.size

def get(self):

start_idx = (self._idx)%self.size

end_idx = start_idx+self.size

return self._buffer[start_idx:end_idx]

#A thread to handle plotting and reading data from the serial port

class Plotter(Thread):

def __init__(self,stream,stop,pause):

Thread.__init__(self)

self.stream = stream

self.fig = plt.figure()

self.ax = plt.axes()

self.size = 100

self.xdata = np.arange(self.size)

self.ydata = RingBuffer(self.size)

self.line, = self.ax.plot(self.ydata.get())

plt.ylim([24,29])

self.stop = stop

self.pause = pause

#The main loop of the thread, invoked with .start()

def run(self):

while not self.stop.is_set():

if self.pause.is_set():

continue

raw_data = self.stream.readline().rstrip()

if len(raw_data) <= 6:

try:

data = float(raw_data)

except ValueError:

print "Not a float"

else:

if data <= 100:

self.ydata.insert(data)

self.line.set_xdata(self.xdata)

self.line.set_ydata(self.ydata.get())

plt.draw()

#sleep statement to reduce processor load

time.sleep(1)

#this is implemented to facilitate use through something like Ipython easily

class Controller(object):

def __init__(self):

#These events control execution of the thread main loop

self.stop = Event()

self.pause = Event()

self.stream = serial.Serial('/dev/tty.usbmodemfa131', 9600)

self.plotter_thread = Plotter(self.stream,self.stop,self.pause)

self.plotter_thread.start()

def main():

con = Controller()

#Loop over terminal input

#possible commands are stop, pause and unpause

while True:

command = raw_input("cmd >>>")

if command == "stop":

con.stop.set()

con.plotter_thread.join()

break

elif command == "pause":

con.pause.set()

elif command == "unpause":

con.pause.clear()

else:

print "unrecognised command"

if __name__ == "__main__":

main()

这将为您提供如下命令行界面:

^{pr2}$

其中下列任何语句应控制绘图仪cmd >>>pause

cmd >>>unpause

cmd >>>stop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值