import serial # 導(dǎo)入串口包
import time? # 導(dǎo)入時(shí)間包
from openpyxl? import Workbook, load_workbook
ser = serial.Serial("COM3", 9600, timeout=5)? # 開啟com3口义钉,波特率9600规肴,超時(shí)5
ser.flushInput()? # 清空緩沖區(qū)
# global i
# i = 1
def main():
? ? while True:
? ? ? ? count = ser.inWaiting()? # 獲取串口緩沖區(qū)數(shù)據(jù)
? ? ? ? if count != 0:
? ? ? ? ? ? recv = ser.read(ser.in_waiting).decode("utf-8")? # 讀出串口數(shù)據(jù),數(shù)據(jù)采用gbk編碼
? ? ? ? ? ? # recv = ser.read(ser.in_waiting).decode("gbk")? # 讀出串口數(shù)據(jù)拖刃,數(shù)據(jù)采用gbk編碼
? ? ? ? ? ? # recv = ser.read(ser.in_waiting) # 讀出串口數(shù)據(jù),數(shù)據(jù)采用gbk編碼
? ? ? ? ? ? wb = load_workbook("excel_test.xlsx")? # 打開 files.xlsx
? ? ? ? ? ? sheet = wb.get_sheet_by_name("Sheet1")? # 設(shè)Sheet1可用
? ? ? ? ? ? sheet.append([recv])
? ? ? ? ? ? # sheet.append([int(recv)*5/1023])
? ? ? ? ? ? wb.save("excel_test.xlsx")
? ? ? ? ? ? print(recv)? # 打印一下子
? ? ? ? ? ? # i += 1
? ? ? ? time.sleep(0.1)? # 延時(shí)0.1秒央碟,免得CPU出問題
if __name__ == '__main__':
? ? main()