01.類比測量儀(LCD)
Arduino UNO 接線Arduino傳感器護罩v5.0接線
void setup() { Serial.begin(9600); //啟用序列埠介面,可以從序列埠視窗抓到數據 lcd.init(); //LCD初始化 lcd.backlight(); //LCD 開啟背光 lcd.clear(); // LCD清除畫面 Serial.println("A0,A1,A2,A3"); //在序列埠顯示 AO,A1,A2,A3,A4}
void loop() {a = analogRead(A0); //讀取類比腳位A0,可以將0~5V 轉化成 0~1023b = analogRead(A1); //讀取類比腳位A1,可以將0~5V 轉化成 0~1023c = analogRead(A2); //讀取類比腳位A2,可以將0~5V 轉化成 0~1023d = analogRead(A3); //讀取類比腳位A3,可以將0~5V 轉化成 0~1023Serial.print(a); //在序列埠顯示a變數的值Serial.print(","); //在序列埠顯示逗點隔開兩個值Serial.print(b); //在序列埠顯示b變數的值Serial.print(","); //在序列埠顯示逗點隔開兩個值Serial.print(c); //在序列埠顯示c變數的值Serial.print(","); //在序列埠顯示逗點隔開兩個值Serial.println(d); //在序列埠顯示d變數的值,並換行lcd.setCursor(0,0); //設定LCD游標至第0行,第0列的位置lcd.print("A0="); //LCD在現在的游標開始顯示 A0= ,每個字元游標會自動前進lcd.print(a); //LCD在現在的游標顯示變數a的值 lcd.print(" "); //LCD在現在的游標顯示空白,這樣可以在位數縮減時,清除多的位數 lcd.setCursor(8,0); //設定LCD游標至第8行,第0列的位置lcd.print("A2="); //LCD在現在的游標開始顯示 A2= ,每個字元游標會自動前進lcd.print(c); //LCD在現在的游標顯示變數c的值lcd.print(" "); //LCD在現在的游標顯示空白,這樣可以在位數縮減時,清除多的位數lcd.setCursor(0,1); //設定LCD游標至第0行,第1列的位置lcd.print("A1="); //LCD在現在的游標開始顯示 A1= ,每個字元游標會自動前進lcd.print(b); //LCD在現在的游標顯示變數b的值 lcd.print(" "); //LCD在現在的游標顯示空白,這樣可以在位數縮減時,清除多的位數 lcd.setCursor(8,1); //設定LCD游標至第8行,第1列的位置lcd.print("A3="); //LCD在現在的游標開始顯示 A3= ,每個字元游標會自動前進lcd.print(d); //LCD在現在的游標顯示變數d的值 lcd.print(" "); //LCD在現在的游標顯示空白,這樣可以在位數縮減時,清除多的位數 delay(100); //每個迴圈延遲0.1秒}
外加Python擷取數據轉存csv檔外掛程式
1.Python的安裝
下載安裝完成後,請到「進階系統設定」 - >「環境變數」 - >「系統變數」 - >「PATH」 - >「編輯」
加上; C:/ Python27
了解此設定之後,即可以熱鍵Window + r呼叫cmd然後輸入python就自動進入Python編譯模式
2.安裝pyserial
安裝方法:無腦安裝一直按下一步
3.安裝PIP INSTALL(本部分不是必要,但是未來可以利用此下載函式庫)
安裝方法:
1.熱鍵窗口+ r然後鍵入cmd後按進入
2.鍵入python後,空一格,然後把get-pip.py拖曳至cmd命令視窗內,如下,按enter
3.回到剛剛第一步我們做過的,到環境變數的PATH裡面加入 ; C:\ Python27 \腳本
未來要下載新的函式庫,只要WINDOW + R - > cmd - > pip install _____即可安裝新的函式
4. NotePad ++
下載點
安裝方法:無腦一直按下一步安裝
5.檔案下載處
(1)點選Arduino_to_csv4.py (點我下載)
(2)如果你想修改,點檔案按滑鼠右鍵 - >用NotePad ++編輯
(3)執行方法:
程式一開始會顯示目前可用的串口(最多五個),
如果被分配到的是COM30請輸入30後,按ENTER鍵。(盡情享受)
(4)儲存結果如下:
會第幾筆資料,日期,時間,四組類比腳位的資料
Python2.7代碼
導入csv
導入序列
導入日期時間
從datetime導入日期時間
從時間導入strftime
import serial.tools.list_ports
coms = str(list(serial.tools.list_ports.comports()))
ports = coms.count('USB VID')
print('串口數:'+ str(端口))
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]
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]
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]
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]
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]
index_head= port5.find(', ')
index_end= port5.find('USB VID')
port5= port5[index_head+3:index_end-4]
if ports >4 :
print(port5)
i = 0
fileDT = datetime.now().strftime('%Y%m%d_%H%M%S')
f = open(fileDT + ".csv", 'ab+' )
w = csv.writer(f,dialect='excel')
w.writerow(["no" , "date" , "time" , "data1" , "data2", "data3", "data4"])
f.close()
arduino = serial.Serial(input("Enter Arduino Serial Port:")-1, 9600) #try change the Serial port
while 1:
f = open(fileDT + ".csv", 'ab+' )
w = csv.writer(f,dialect='excel')
cmd = arduino.readline().strip()
csvdata=cmd.split(',')
print(cmd)
i += 1
data = [i , datetime.now().strftime('%Y/%m/%d'), datetime.now().strftime('%H:%M:%S')] + csvdata
w.writerow(data)
f.close()
Python3.6 Code
import csv
import serial
import datetime
from datetime import datetime
from time import strftime
import win32com.client
i = 0
fileDT = datetime.now().strftime('%Y%m%d_%H%M%S')
f = open(fileDT + ".csv", 'a',newline='' )
w = csv.writer(f,dialect='excel')
w.writerow(["no" , "date" , "time" , "data1" , "data2", "data3", "data4"])
f.close()
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
while 1:
f = open(fileDT + ".csv", 'a',newline='' )
w = csv.writer(f,dialect='excel')
cmd = arduino.readline().strip().decode('ascii')
csvdata=cmd.split(',')
print(cmd)
i += 1
data = [i , datetime.now().strftime('%Y/%m/%d'), datetime.now().strftime('%H:%M:%S')] + csvdata
w.writerow(data)
f.close()
6. 懶人包(請解壓縮後,按Arduino2CSV.exe 執行)
7.執行分析圖形工具 (下載點)
程式碼參考
import time
import numpy as np
import matplotlib.pyplot as pyplot
import win32com.client
from tkinter import *
import tkinter as tk
import serial
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
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
def onStartButtonPress():
while(1):
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)
f.canvas.draw()
pyplot.pause(0.001) #可以使畫面不當機,一定要加 # update the plot
window.update()
else:
flag.set(True)
break
def onPauseButtonPress():
flag.set(False)
def onExitButtonPress():
print ("Exiting....")
onPauseButtonPress()
arduino.close()
pyplot.close(f)
window.quit()
window.destroy()
print ("Done.")
sys.exit()
# Create flag to work with indefinite while loop
if __name__ == '__main__':
window = Tk()
frame1= Frame(window)
frame1.pack(side=TOP,fill=X,expand=1)
Label(frame1,text='控制介面',font=("微軟正黑體",12),bg='pink').pack(side=LEFT,fill=Y)
startButton = Button(frame1, fg='red',font=("微軟正黑體",12),text="Start",command=onStartButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
pauseButton = Button(frame1, fg='blue',font=("微軟正黑體",12),text="Pause",command=onPauseButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
exitButton = Button(frame1, fg='dark green',font=("微軟正黑體",12),text="Exit",command=onExitButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
frame2= Frame(window)
frame2.pack(side=TOP,fill=Y,expand=1)
f = Figure(figsize=(5, 4), dpi=100)
ax = f.add_subplot(111)
line1, = ax.plot(x, y1, '-', lw=3) #改變線條1樣式
line2, = ax.plot(x, y2, '-', lw=3) #改變線條2樣式
line3, = ax.plot(x, y3, '-', lw=3) #改變線條3樣式
line4, = ax.plot(x, y4, '-', lw=3) #改變線條4樣式
canvas = FigureCanvasTkAgg(f, master=frame2)
canvas.show()
canvas.get_tk_widget().pack(side=TOP,fill=Y,expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, frame2)
toolbar.update()
canvas._tkcanvas.pack(side=TOP,fill=BOTH,expand=1)
flag = BooleanVar(window)
flag.set(True)
ax.set_xlabel('number') #改變x軸標題
ax.set_ylabel('AnalogRead') #改變y軸標題
ax.set_title('Title') #改變圖表標題
ax.grid(axis = 'y')
#pyplot.ion()
#pyplot.show()
window.attributes("-topmost", 1)
window.mainloop()
選單版 (下載點)
程式碼參考
import time
import numpy as np
import matplotlib.pyplot as pyplot
import win32com.client
from tkinter import *
import tkinter as tk
import serial
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
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
def selectport():
global arduino
port=opvar.get()
if port.find('(')>-1 and port.find(')')>-1:
winport = port[port.find('(')+1:port.find(')')]
arduino = serial.Serial(winport, 9600)
def disconnect():
arduino.close()
def onStartButtonPress():
while(1):
if flag.get():
global i,arduino
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)
f.canvas.draw()
pyplot.pause(0.001) #可以使畫面不當機,一定要加 # update the plot
window.update()
else:
flag.set(True)
break
def onPauseButtonPress():
flag.set(False)
def onExitButtonPress():
print ("Exiting....")
onPauseButtonPress()
arduino.close()
pyplot.close(f)
window.quit()
window.destroy()
print ("Done.")
sys.exit()
# Create flag to work with indefinite while loop
if __name__ == '__main__':
window = Tk()
frame1= Frame(window)
frame1.pack(side=TOP,fill=BOTH,expand=1)
Label(frame1,text='序列埠',font=("微軟正黑體",12),bg='yellow').pack(side=LEFT,fill=BOTH)
opvar = StringVar()
opvar.set('點我選擇序列埠')
w = OptionMenu(frame1, opvar, *(serials))
w.config(width=30,font=("微軟正黑體",12))
w.pack(side=LEFT,fill=BOTH,expand=1)
Button(frame1,text='連線',font=("微軟正黑體",12),command=selectport).pack(side=LEFT,fill=BOTH)
Button(frame1,text='斷線',font=("微軟正黑體",12),command=disconnect).pack(side=LEFT,fill=BOTH)
frame3= Frame(window)
frame3.pack(side=TOP,fill=Y,expand=1)
f = Figure(figsize=(6, 4), dpi=90)
ax = f.add_subplot(111)
line1, = ax.plot(x, y1, '-', lw=3) #改變線條1樣式
line2, = ax.plot(x, y2, '-', lw=3) #改變線條2樣式
line3, = ax.plot(x, y3, '-', lw=3) #改變線條3樣式
line4, = ax.plot(x, y4, '-', lw=3) #改變線條4樣式
canvas = FigureCanvasTkAgg(f, master=frame3)
canvas.show()
canvas.get_tk_widget().pack(side=TOP,fill=Y,expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, frame3)
toolbar.update()
canvas._tkcanvas.pack(side=TOP,fill=BOTH,expand=1)
flag = BooleanVar(window)
flag.set(True)
ax.grid(axis = 'y')
ax.set_xlabel('number') #改變x軸標題
ax.set_ylabel('AnalogRead') #改變y軸標題
#ax.set_title('Title') #改變圖表標題
frame2= Frame(window)
frame2.pack(side=TOP,fill=X,expand=1)
Label(frame2,text='控制介面',font=("微軟正黑體",12),bg='pink').pack(side=LEFT,fill=Y)
startButton = Button(frame2, fg='red',font=("微軟正黑體",12),text="Start",command=onStartButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
pauseButton = Button(frame2, fg='blue',font=("微軟正黑體",12),text="Pause",command=onPauseButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
exitButton = Button(frame2, fg='dark green',font=("微軟正黑體",12),text="Exit",command=onExitButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
window.attributes("-topmost", 1)
window.mainloop()
選單+繪圖+顯示介面+控制元件(點我下載)
參考程式碼
import csv
import time
import numpy as np
import matplotlib.pyplot as pyplot
import win32com.client
from tkinter import *
import tkinter as tk
import serial
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import datetime
from datetime import datetime
from time import strftime
x = []
y1 = []
y2 = []
y3 = []
y4 = []
csv_text = []
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])
fileDT = datetime.now().strftime('%Y%m%d_%H%M%S')
f = open(fileDT + ".csv", 'a',newline='' )
w = csv.writer(f,dialect='excel')
w.writerow(["data1" , "data2", "data3", "data4"])
f.close()
#arduino = serial.Serial('COM'+input('Please Enter the Arduino Port:'), 9600) #設定Serial Port
def selectport():
global arduino
port=opvar.get()
if port.find('(')>-1 and port.find(')')>-1:
winport = port[port.find('(')+1:port.find(')')]
arduino = serial.Serial(winport, 9600)
def disconnect():
arduino.close()
def onStartButtonPress():
while(1):
if flag.get():
global i,arduino
i += 1
time.sleep(0.005)
cmd = arduino.readline().strip().decode('ascii') #Arduino傳來的CSV檔並去掉無效字
print(cmd)
text.insert(END,cmd)
text.insert(END,'\n')
text.see(END)
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容器的最後方
csv_text.append(int(cmd[0]))
csv_text.append(int(cmd[1]))
csv_text.append(int(cmd[2]))
csv_text.append(int(cmd[3]))
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)
f.canvas.draw()
pyplot.pause(0.001) #可以使畫面不當機,一定要加 # update the plot
window.update()
else:
flag.set(True)
break
def onPauseButtonPress():
flag.set(False)
def onExitButtonPress():
global csv_text,f,w
print ("Exiting....")
onPauseButtonPress()
arduino.close()
pyplot.close(f)
for i in range(0,len(csv_text),4):
f = open(fileDT + ".csv", 'a',newline='' )
w = csv.writer(f,dialect='excel')
w.writerow([csv_text[i],csv_text[i+1],csv_text[i+2],csv_text[i+3]])
f.close()
window.quit()
window.destroy()
print ("Done.")
sys.exit()
# Create flag to work with indefinite while loop
if __name__ == '__main__':
window = Tk()
frame1= Frame(window)
frame1.pack(side=TOP,fill=BOTH,expand=1)
frame2= Frame(window)
frame2.pack(side=TOP,fill=Y,expand=1)
frame3= Frame(window)
frame3.pack(side=TOP,fill=Y,expand=1)
frame4= Frame(window)
frame4.pack(side=TOP,fill=X,expand=1)
#框架1
Label(frame1,text='序列埠',font=("微軟正黑體",12),bg='yellow').pack(side=LEFT,fill=BOTH)
opvar = StringVar()
opvar.set('1.請先點我選擇序列埠')
w = OptionMenu(frame1, opvar, *(serials))
w.config(width=30,font=("微軟正黑體",12))
w.pack(side=LEFT,fill=BOTH,expand=1)
Button(frame1,text='2.連線',font=("微軟正黑體",12),command=selectport).pack(side=LEFT,fill=BOTH)
Button(frame1,text='斷線',font=("微軟正黑體",12),command=disconnect).pack(side=LEFT,fill=BOTH)
#框架2
f = Figure(figsize=(6, 4), dpi=90)
ax = f.add_subplot(111)
ax.grid(axis = 'y')
ax.set_xlabel('number') #改變x軸標題
ax.set_ylabel('AnalogRead') #改變y軸標題
#ax.set_title('Title') #改變圖表標題
line1, = ax.plot(x, y1, '-', lw=3) #改變線條1樣式
line2, = ax.plot(x, y2, '-', lw=3) #改變線條2樣式
line3, = ax.plot(x, y3, '-', lw=3) #改變線條3樣式
line4, = ax.plot(x, y4, '-', lw=3) #改變線條4樣式
canvas = FigureCanvasTkAgg(f, master=frame2)
canvas.show()
canvas.get_tk_widget().pack(side=TOP,fill=Y,expand=1)
scrollbar = Scrollbar(frame2)
scrollbar.pack(side = RIGHT, fill = Y)
text = Text(frame2, width = 20, height = 10, wrap = WORD, yscrollcommand = scrollbar.set)
text.configure(background='floral white')
text.pack(side=LEFT,expand=1,fill=BOTH)
scrollbar.config(command = text.yview)
#框架3
canvas._tkcanvas.pack(side=LEFT,fill=BOTH,expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, frame3)
toolbar.update()
#框架4
Label(frame4,text='控制介面',font=("微軟正黑體",12),bg='pink').pack(side=LEFT,fill=Y)
startButton = Button(frame4, fg='red',font=("微軟正黑體",12),text="3.開始",command=onStartButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
pauseButton = Button(frame4, fg='blue',font=("微軟正黑體",12),text="4.暫停",command=onPauseButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
exitButton = Button(frame4, fg='dark green',font=("微軟正黑體",12),text="5.離開並存成CSV",command=onExitButtonPress).pack(side=LEFT,fill=BOTH,expand=1)
flag = BooleanVar(window)
flag.set(True)
window.attributes("-topmost", 1)
window.mainloop()