使用python實現串口的讀取和保存

import time
import serial
import chardet

def ser_get():
    '''串口連接'''

    portx = 'com3' #端口號

    bps = 115200 # 波特率

    timeout = None #超時時間設置,None代表永遠等待操作

    ser = serial.Serial(portx,bps,timeout = timeout) #打開串口,並得到串口對象
    #print('串口詳情參數:',ser)

    return  ser

def ser_read():
    '''串口讀取'''
    print('正在讀取串口內容!')
    data  = ''
    while True:
        data = ser_get().reanline()  #獲取串口內容
        print('***********')
        time1 = time.time()
        t = time.ctime()
        print(t,':')
        print(data)
        with open('D:/test.txt','a') as f:
            f.writelines(t)
            f.writelines(':\n')
            try:
                f.writelines(data.decode(encofing = 'utf-8'))
            except Exception as e :
                print(e)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章