python 中Arduino串口傳輸數(shù)據(jù)到電腦并保存至excel表格
起因:學(xué)校運河杯報了個項目,制作一個天氣預(yù)測的裝置。我用arduino跑了BME280模塊,用藍牙模塊實現(xiàn)兩塊arduino主從機透傳。但是為了分析,還需要提取出數(shù)據(jù)。因此我用python寫了個上位機程序,用pyserial模塊實現(xiàn)arduiho和電腦的串口通訊,再用xlwt模塊寫入excel表格,用time模塊獲取時間作為excel的文件名。
import xlwt import time import serial #設(shè)置表格樣式 def set_style(name,height,bold=False): style = xlwt.XFStyle() font = xlwt.Font() font.name = name font.bold = bold font.color_index = 4 font.height = height style.font = font return style #寫Excel def write_excel(): if serial.isOpen(): print ('串口已打開\n') f = xlwt.Workbook() sheet1 = f.add_sheet('arduino_data',cell_overwrite_ok=True) row0 = ["temp","pres","hum"] time1=time.localtime(time.time()) #寫第一行 for i in range(len(row0)): sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) i=1 time.sleep(5) serial.flushInput() while True: try: size = serial.inWaiting() if size != 0: response = serial.read(size) # 讀取內(nèi)容并顯示 s=response.decode('utf-8').rstrip('\r\n').split('\t') if len(s)!=3: serial.flushInput() continue else: try: for j in range(len(s)): sheet1.write(i,j,int(s[j]),set_style('Times New Roman',220,False)) print(s) serial.flushInput() # 清空接收緩存區(qū) i = i+1 time.sleep(0.5) except ValueError: serial.flushInput() continue except KeyboardInterrupt: time2=time.localtime(time.time()) f.save(r'C:\Users\10020\Desktop\arduino_data\{0}.{1}_{2:0>2d}.{3:0>2d}.{4:0>2d}-{5}.{6}_{7:0>2d}.{8:0>2d}.{9:0>2d}.xls'.format\ (time1[1],time1[2],time1[3],time1[4],time1[5], time2[1],time2[2],time2[3],time2[4],time2[5])) serial.close() print(time1) print(time2) quit() if __name__ == '__main__': serial = serial.Serial('COM3',9600,timeout=2) write_excel()
運行代碼后會一直從串口讀取arduino的數(shù)據(jù),然后寫入excel。按Ctrl+c來中止代碼進程,此時會在C:\Users\10020\Desktop\arduino_data\這個文件夾下生成以“開始運行時間-結(jié)束運行時間”為名稱的xls文件。
代碼的運行效果:
需要注意的是:
- 串口和波特率根據(jù)電腦上顯示的COM口和設(shè)置的arduino波特率決定
- arduino是通過串口發(fā)送字節(jié)串到電腦,需要編碼成utf-8再對字符串進行處理
- 每一次接受完數(shù)據(jù)要清楚數(shù)據(jù)緩存
總結(jié)
以上所述是小編給大家介紹的python Arduino串口傳輸數(shù)據(jù)到電腦并保存至excel表格,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Python Json模塊中dumps、loads、dump、load函數(shù)介紹
本篇文章主要介紹了Python Json模塊中dumps、loads、dump、load函數(shù)介紹,詳細的介紹了這幾種函數(shù)的用法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05Python中執(zhí)行調(diào)用JS的多種實現(xiàn)方法總結(jié)
這篇文章主要給大家介紹了關(guān)于Python中執(zhí)行調(diào)用JS的多種實現(xiàn)方法,在一些特殊的python應(yīng)用場景下需要逆向執(zhí)行javascript代碼塊或者.js文件,需要的朋友可以參考下2023-08-08Python實現(xiàn)多維數(shù)據(jù)分析的示例詳解
多維數(shù)據(jù)分析是對數(shù)據(jù)的信息分析,它考慮了許多關(guān)系,這篇文章主要為大家詳細介紹了一些使用Python分析多維/多變量數(shù)據(jù)的基本技術(shù),希望對大家有所幫助2023-11-11關(guān)于python3.9安裝wordcloud出錯的問題及解決辦法
這篇文章主要介紹了關(guān)于python3.9安裝wordcloud出錯的問題及解決辦法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11