2. matplotlib
以下程式碼可以抓取Arduino傳來的csv檔案,並繪圖
#!/usr/bin/python
#-*- coding: utf-8 -*-
import time
import numpy as np
import matplotlib.pyplot as plt
import serial
import serial.tools.list_ports
coms = str(list(serial.tools.list_ports.comports()))
ports = coms.count('USB VID')
print('Number of Serial Port: ' + str(ports)) #顯示可用的Serual port數量
index_0= coms.find('USB VID')
index_1= coms.find('), (', index_0+5, len(coms))
index_2= coms.find('), (', index_1+5, len(coms))
index_3= coms.find('), (', index_2+5, len(coms))
index_4= coms.find('), (', index_3+5, len(coms))
port1= coms[1 : index_0+1] #擷取第一個Serial Port裝置
index_head= port1.find(', ')
index_end= port1.find('USB VID')
port1= port1[index_head+3:index_end-4]
print(port1)
port2= coms[index_1+3 : len(coms)-1] #擷取第二個Serial Port裝置
index_head= port2.find(', ')
index_end= port2.find('USB VID')
port2= port2[index_head+3:index_end-4]
if ports >1 :
print(port2)
port3= coms[index_2+3 : len(coms)-1] #擷取第三個Serial Port裝置
index_head= port3.find(', ')
index_end= port3.find('USB VID')
port3= port3[index_head+3:index_end-4]
if ports >2 :
print(port3)
port4= coms[index_3+3 : len(coms)-1] #擷取第四個Serial Port裝置
index_head= port4.find(', ')
index_end= port4.find('USB VID')
port4= port4[index_head+3:index_end-4]
if ports >3 :
print(port4)
port5= coms[index_4+3 : len(coms)-1] #擷取第五個Serial Port裝置
index_head= port5.find(', ')
index_end= port5.find('USB VID')
port5= port5[index_head+3:index_end-4]
if ports >4 :
print(port5)
arduino = serial.Serial(input("Enter Arduino Serial Port:")-1, 9600) #設定Serial Port
fig=plt.figure()
plt.xlabel('number') #改變x軸標題
plt.ylabel('AnalogRead') #改變y軸標題
plt.title('Title') #改變圖表標題
plt.grid(axis = 'y')
plt.ion()
plt.show()
ax = fig.add_subplot(111)
x = []
y1 = []
y2 = []
y3 = []
y4 = []
i = 0
line1, = ax.plot(x, y1, 'o-', lw=3) #改變線條1樣式
line2, = ax.plot(x, y2, 'o-') #改變線條2樣式
line3, = ax.plot(x, y3, 'o-') #改變線條3樣式
line4, = ax.plot(x, y4, 'o-') #改變線條4樣式
try :
while 1:
time.sleep(0.005)
cmd = arduino.readline().strip() #Arduino傳來的CSV檔並去掉無效字
print(cmd)
cmd=cmd.split(',') #將csv格式資料拆到容器cmd的四個位置
x.append(i) #插新點在x容器的最後方
y1.append(int(cmd[0])) #插新點在y1容器的最後方
y2.append(int(cmd[1])) #插新點在y2容器的最後方
y3.append(int(cmd[2])) #插新點在y3容器的最後方
y4.append(int(cmd[3])) #插新點在y4容器的最後方
if i > 100 : #可以保持畫面由左到右共100點,取消掉這一串後圖形可以累加數值
x.pop(0) #刪掉x容器的第一個數值
y1.pop(0) #刪掉y1容器的第一個數值
y2.pop(0) #刪掉y2容器的第一個數值
y3.pop(0) #刪掉y3容器的第一個數值
y4.pop(0) #刪掉y4容器的第一個數值
line1.set_data(x, y1)
line2.set_data(x, y2)
line3.set_data(x, y3)
line4.set_data(x, y4)
i+=1
ax.relim()
ax.autoscale_view(True,True,True)
fig.canvas.draw()
plt.pause(0.01) #可以使畫面不當機,一定要加
except KeyboardInterrupt:
print('exit')
plt.savefig('c:\\plot.png',dpi=200,format='png')
raw_input('press Enter to close')
https://matplotlib.org/tutorials/introductory/sample_plots.html
https://matplotlib.org/gallery/index.html#api-examples
#!/usr/bin/python
#-*- coding: utf-8 -*-
import time
import numpy as np
import matplotlib.pyplot as pyplot
import win32com.client
from tkinter import *
import tkinter as tk
import serial
window = Tk()
x = []
y1 = []
y2 = []
y3 = []
y4 = []
i = 0
wmi = win32com.client.GetObject("winmgmts:")
serials=[]
for serial_1 in wmi.InstancesOf("Win32_SerialPort"):
serials.append(serial_1.Name)
for i in range(0, len(serials)):
print(serials[i])
arduino = serial.Serial('COM'+input('Please Enter the Arduino Port:'), 9600) #設定Serial Port
fig=pyplot.figure()
def onStartButtonPress():
while True:
if flag.get():
global i
i += 1
time.sleep(0.005)
cmd = arduino.readline().strip().decode('ascii') #Arduino傳來的CSV檔並去掉無效字
print(cmd)
cmd=cmd.split(',') #將csv格式資料拆到容器cmd的四個位置
x.append(int(i)) #插新點在x容器的最後方
y1.append(int(cmd[0])) #插新點在y1容器的最後方
y2.append(int(cmd[1])) #插新點在y2容器的最後方
y3.append(int(cmd[2])) #插新點在y3容器的最後方
y4.append(int(cmd[3])) #插新點在y4容器的最後方
if i > 100 : #可以保持畫面由左到右共100點,取消掉這一串後圖形可以累加數值
x.pop(0) #刪掉x容器的第一個數值
y1.pop(0) #刪掉y1容器的第一個數值
y2.pop(0) #刪掉y2容器的第一個數值
y3.pop(0) #刪掉y3容器的第一個數值
y4.pop(0) #刪掉y4容器的第一個數值
line1.set_data(x, y1)
line2.set_data(x, y2)
line3.set_data(x, y3)
line4.set_data(x, y4)
ax.relim()
ax.autoscale_view(True,True,True)
fig.canvas.draw()
pyplot.pause(0.01) #可以使畫面不當機,一定要加 # update the plot
window.update()
else:
flag.set(True)
break
def onPauseButtonPress():
flag.set(False)
def onExitButtonPress():
print ("Exiting....")
onPauseButtonPress()
arduino.close()
pyplot.close(fig)
window.quit()
window.destroy()
print ("Done.")
sys.exit()
# Create flag to work with indefinite while loop
flag = BooleanVar(window)
flag.set(True)
pyplot.xlabel('number') #改變x軸標題
pyplot.ylabel('AnalogRead') #改變y軸標題
pyplot.title('Title') #改變圖表標題
pyplot.grid(axis = 'y')
pyplot.ion()
pyplot.show()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y1, 'o-', lw=3) #改變線條1樣式
line2, = ax.plot(x, y2, 'o-') #改變線條2樣式
line3, = ax.plot(x, y3, 'o-') #改變線條3樣式
line4, = ax.plot(x, y4, 'o-') #改變線條4樣式
startButton = Button(window, text="Start",command=onStartButtonPress).grid(column=1, row=2)
pauseButton = Button(window, text="Pause",command=onPauseButtonPress).grid(column=2, row=2)
exitButton = Button(window,text="Exit",command=onExitButtonPress).grid(column=3, row=2)
window.attributes("-topmost", 1)
window.mainloop()
先參考,待研究