Matplot实时绘制cpu负载

时间:2015-04-28 07:41:02

标签: python python-3.x

我想使用mat plot library显示CPU。我的python代码每1秒通过串口发送CPU负载到目标板和输出我需要使用绘图显示它。我遇到了一些例子,但我没有得到如何集成我的代码。我是python的新手。这是我写的代码。

import serial, time, threading, multiprocessing,sys
import numpy as np
from matplotlib import pyplot as plt
from collections import deque
import csv

ser = serial.Serial(
port='COM4',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS  
)
class analogData:
# constr
   def __init__(self, maxLen):
      self.ax = deque([0.0]*maxLen)
      self.ay = deque([0.0]*maxLen)
      self.maxLen = maxLen

# ring buffer
  def addToBuf(self, buf, val):
      if len(buf) < self.maxLen:
          buf.append(val)
      else:
          buf.pop()
          buf.appendleft(val)

# add data
  def add(self, data):
      assert(len(data) == 2)
      self.addToBuf(self.ax, data[0])
      self.addToBuf(self.ay, data[1])
# plot class

class analogPlot:
# constr
   def __init__(self, analogData):
   # set plot to animated
      plt.ion()
      self.axline, = plt.plot(analogData.ax)
      self.ayline, = plt.plot(analogData.ay)
      plt.ylim([0, 1023])
      plt.show()

# update plot
  def update(self, analogData):
     self.axline.set_ydata(analogData.ax)
     self.ayline.set_ydata(analogData.ay)
     plt.draw()


  def serialWrite(cmd: str):
     l=0
     ser.flushOutput()
     time.sleep(0.04)
     while l < len(cmd):
        ser.write(cmd[l].encode())
        time.sleep(0.02)
        ser.flushInput()
        l=l+1
    ser.write('\r'.encode())


def serialRead():
    time.sleep(0.065)
    out=""
    while ser.inWaiting() > 0:
        out += ser.read().decode("utf-8")
    return out

def read_from_serial():
   #pool_sema.acquire()
    out=""
    serialWrite("cpu")
    out=serialRead() 
    data = [float(val) for val in out.split()]

    analogData.add(analogData,data)
    analogPlot.update(analogData) 
    print (data)
    #pool_sema.release()
    threading.Timer(1, read_from_serial).start()


def commandInput():
   while True:        
        out=""
        out=input()
        serialWrite(out)
        out=""
        out=serialRead()
        print (out)



if __name__ == "__main__":
   serial_thread = threading.Thread(target = read_from_serial())
   main_thread=threading.Thread(target = commandInput())
   analogData = analogData(100)
   analogPlot = analogPlot(analogData) 
   serial_thread.start()
   main_thread.start()

请给我建议我做错的事情。

0 个答案:

没有答案