python串口如何讀取byte類型數(shù)據(jù)并訪問
python串口讀取byte類型數(shù)據(jù)并訪問
以讀取SBT力傳感器數(shù)據(jù)為例
#! usr/bin/env pyhton # coding:utf-8 import serial import time import csv import os originaltime = 0.0 starttime = 0.0 endtime = 0.0 endtimebefore = 0.0 def savedis(force , csvfile): ? ? f = open(csvfile, 'a', encoding='utf-8', newline='') ?# 'w'覆蓋寫 'a'追加寫 ? ? csv_writer = csv.writer(f) ? ? global endtime ? ? time_head = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime)) ? ? time_sec = (endtime - int(endtime)) * 1000 ? ? timesample = "%s.%03d" % (time_head, time_sec) ? ? csv_writer.writerow([timesample, str(force)]) ? ? # f.close() def main(): ? ? # 文件處理 ? ? current_path = os.path.abspath(__file__)[:-len('sbt_test.py')] ? ? currenttime = time.localtime(time.time()) ? ? csvfile = current_path + str(currenttime.tm_hour) + '-' + str(currenttime.tm_min) +'-'+ str(currenttime.tm_sec) + '.csv' ? ? f = open(csvfile, 'a', encoding='utf-8', newline='') ?# 'w'覆蓋寫 'a'追加寫 ? ? csv_writer = csv.writer(f) ? ? csv_writer.writerow(['timestamp(ms)', 'display(N)']) ? ? f.close() ? ? # 串口聲明 ? ? port = 'COM7' #根據(jù)設(shè)備管理器的端口號更改 ? ? baud = 115200 ? ? timex = 0.02 ?# 超時設(shè)置,None:永遠等待操作,0為立即返回請求結(jié)果,其他值為等待超時時間(單位為秒) ? ? global starttime ? ? global endtime ? ? global endtimebefore ? ? sbtforce = serial.Serial(port, baud, timeout=timex) #此行不能放在循環(huán)內(nèi),因為耗時長 ? ? sendmessage = sbtforce.write(bytes.fromhex('FE010701000001CFFCCCFF')) ? ? offset = 20 ?# 收到的數(shù)據(jù)跟放大器上的示數(shù)不對應(yīng),需要減去一個偏差值,根據(jù)示數(shù)調(diào)整 ? ? while True: ? ? ? ? endtime = time.time() ? ? ? ? startdata = sbtforce.read(1) ? ? ? ? if startdata == b'\xFE': ? ? ? ? ? ? buffer = sbtforce.read(10) ? ? ? ? ? ? if (buffer[9] == 255): ? ? ? ? ? ? ? ? print("buffer=",buffer) ? ? ? ? ? ? ? ? force = buffer[2:6] ? ? ? ? ? ? ? ? print('force = ',force) ? ? ? ? ? ? ? ? force = force[0] << 24 | force[1] << 16 | force[2] << 8 | force[3] ? ? ? ? ? ? ? ? if force > 100000000: ? ? ? ? ? ? ? ? ? ? force = force - 2**32 - offset ? ? ? ? ? ? ? ? if force > 0: ? ? ? ? ? ? ? ? ? ? force -= offset ? ? ? ? ? ? ? ? force = force / 100.0 ? ? ? ? ? ? ? ? print('壓力值:', force) ? ? ? ? ? ? ? ? savedis(force, csvfile) if __name__ == '__main__': ? ? main()
聲明串口對象:
sbtforce = serial.Serial(port, baud, timeout=timex)
然后從串口讀取字節(jié),比如一次讀取10個字節(jié):
data = sbtforce.read(10)
然后,假如要訪問data的第一個字節(jié),如果直接寫
data[0]
那么返回的將是第一個字節(jié)對應(yīng)的整形,也就是說type(data[0])=int
那么如何拿到byte類型呢,可以這樣做:
data[0:1]
這樣返回的將會是字節(jié)類型的第一個字節(jié)的數(shù)據(jù)。
python串口使用問題
python串口數(shù)據(jù)
python串口收發(fā)的都是bytes類型數(shù)據(jù),即使是字符串,也會編碼器后進行傳輸
設(shè)置串口,并打開
ser1 = serial.Serial(port='/dev/ttyUSB1', baudrate=115200, bytesize=8, parity='N', stopbits=1)
這樣創(chuàng)建一個串口對象后,串口直接自動打開
python中發(fā)送數(shù)據(jù)使用write()函數(shù)
s.write(data) #不指明編碼方式,直接發(fā)送 s.write(data.encode('utf-8')) # utf-8 編碼發(fā)送 s.write(data.encode('hex')) # 轉(zhuǎn)成16進制后發(fā)送
python中接收數(shù)據(jù)使用read_all()和read(len)函數(shù)
read_all()
會讀取緩沖區(qū)內(nèi)的數(shù)據(jù)read(len)
讀取len長的數(shù)據(jù)
python2和python3之間的區(qū)別
bytes是Python 3中特有的,Python 2 里不區(qū)分bytes和str。bytes是byte的序列,而str是unicode的序列。
python2中:
str 使用encode()方法轉(zhuǎn)化為
bytesbytes通過decode()轉(zhuǎn)化為str
在python3中:常見容易忽略的錯誤
串口接收到數(shù)據(jù)很亂,更預(yù)計差別很大,首先檢查波特率對不對
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解pandas的外部數(shù)據(jù)導(dǎo)入與常用方法
這篇文章主要介紹了詳解pandas的外部數(shù)據(jù)導(dǎo)入與常用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-05-05教你用Django將前端的數(shù)據(jù)存入Mysql數(shù)據(jù)庫
這篇文章主要給大家介紹了關(guān)于如何用Django將前端的數(shù)據(jù)存入Mysql數(shù)據(jù)庫的相關(guān)資料,文中通過圖文以及示例代碼介紹的非常詳細,對大家學(xué)習或者使用Django具有一定的參考學(xué)習價值,需要的朋友可以參考下2021-11-11Python實現(xiàn)對Excel文件中不在指定區(qū)間內(nèi)的數(shù)據(jù)加以去除的方法
這篇文章主要介紹了基于Python語言,讀取Excel表格文件,基于我們給定的規(guī)則,對其中的數(shù)據(jù)加以篩選,將不在指定數(shù)據(jù)范圍內(nèi)的數(shù)據(jù)剔除,保留符合我們需要的數(shù)據(jù)的方法,需要的朋友可以參考下2023-08-08python應(yīng)用程序在windows下不出現(xiàn)cmd窗口的辦法
這篇文章主要介紹了python應(yīng)用程序在windows下不出現(xiàn)cmd窗口的辦法,適用于python寫的GTK程序并用py2exe編譯的情況下,需要的朋友可以參考下2014-05-05Python編程使用*解包和itertools.product()求笛卡爾積的方法
這篇文章主要介紹了Python編程使用*解包和itertools.product()求笛卡爾積的方法,涉及Python列表轉(zhuǎn)換及itertools.product()求笛卡爾積相關(guān)操作技巧,需要的朋友可以參考下2017-12-12python調(diào)用Matplotlib繪制分布點圖
這篇文章主要為大家詳細介紹了python調(diào)用Matplotlib繪制分布點圖,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10