最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解

 更新時間:2019年06月12日 09:30:50   作者:返回主頁 木子宣  
今天小編就為大家分享一篇對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

其實網(wǎng)上已經(jīng)有許多python語言書寫的串口,但大部分都是python2寫的,沒有找到一個合適的python編寫的串口助手,只能自己來寫一個串口助手,由于我只需要串口能夠接收讀取數(shù)據(jù)就可以了,故而這個串口助手只實現(xiàn)了數(shù)據(jù)的接收讀取。

創(chuàng)建串口助手首先需要創(chuàng)建一個類,重構(gòu)類的實現(xiàn)過程如下:

#coding=gb18030

import threading
import time
import serial

class ComThread:
 def __init__(self, Port='COM3'):
 #構(gòu)造串口的屬性
  self.l_serial = None
  self.alive = False
  self.waitEnd = None
  self.port = Port
  self.ID = None
  self.data = None
 #定義串口等待的函數(shù)
 def waiting(self):
  if not self.waitEnd is None:
   self.waitEnd.wait()

 def SetStopEvent(self):
  if not self.waitEnd is None:
   self.waitEnd.set()
  self.alive = False
  self.stop()
 #啟動串口的函數(shù)
 def start(self):
  self.l_serial = serial.Serial()
  self.l_serial.port = self.port
  self.l_serial.baudrate = 115200
  #設(shè)置等待時間,若超出這停止等待
  self.l_serial.timeout = 2
  self.l_serial.open()
  #判斷串口是否已經(jīng)打開
  if self.l_serial.isOpen():
   self.waitEnd = threading.Event()
   self.alive = True
   self.thread_read = None
   self.thread_read = threading.Thread(target=self.FirstReader)
   self.thread_read.setDaemon(1)
   self.thread_read.start()
   return True
  else:
   return False

創(chuàng)建好類后,就要實現(xiàn)串口讀取的功能,其讀取數(shù)據(jù)的函數(shù)如下:

首先要創(chuàng)建一個字符串來存放接收到的數(shù)據(jù):

   data = ''
   data = data.encode('utf-8')#由于串口使用的是字節(jié),故而要進行轉(zhuǎn)碼,否則串口會不識別

在創(chuàng)建好變量來接收數(shù)據(jù)后就要開始接收數(shù)據(jù):

n = self.l_serial.inWaiting()#獲取接收到的數(shù)據(jù)長度
   if n: 
     #讀取數(shù)據(jù)并將數(shù)據(jù)存入data
     data = data + self.l_serial.read(n)
     #輸出接收到的數(shù)據(jù)
     print('get data from serial port:', data)
     #顯示data的類型,便于如果出錯時檢查錯誤
     print(type(data))

將數(shù)據(jù)接收完后,就要對接收到的數(shù)據(jù)進行處理,提取出有用信息,由于下位機使用的協(xié)議不一樣,因此處理的方法也不一樣,我使用的協(xié)議是**+ID+*Data+*,因此我的提取方法如下:

#獲取還沒接收到的數(shù)據(jù)長度
n = self.l_serial.inWaiting()
#判斷是否已經(jīng)將下位機傳輸過來的數(shù)據(jù)全部提取完畢,防止之前沒有獲取全部數(shù)據(jù)
if len(data)>0 and n==0:
 try:
  #將數(shù)據(jù)轉(zhuǎn)換為字符型
  temp = data.decode('gb18030')
  #輸出temp類型,看轉(zhuǎn)碼是否成功
  print(type(temp))
  #輸出接收到的數(shù)據(jù)
  print(temp)
  將數(shù)據(jù)按換行分割并輸出
  car,temp = str(temp).split("\n",1)
  print(car,temp)
 
  #將temp按':'分割,并獲取第二個數(shù)據(jù)
  string = str(temp).strip().split(":")[1]
  #由于前面分割后的數(shù)據(jù)類型是列表,因此需要轉(zhuǎn)換成字符串,而后按照'*'分割,得到的也就是我們需要的Id和data
  str_ID,str_data = str(string).split("*",1)
 
  print(str_ID)
  print(str_data)
  print(type(str_ID),type(str_data))
  #判斷data最后一位是否是'*',若是則退出,若不是則輸出異常
  if str_data[-1]== '*':
   break
  else:
   print(str_data[-1])
   print('str_data[-1]!=*')
 except:
  print("讀卡錯誤,請重試!\n")

其輸出結(jié)果為:

get data from serial port:b'ID:4A622E29\n\xbf\xa8\xd6\xd0\xbf\xe924\xca\xfd\xbe\xdd\xce\xaa:1*80*\r\n'
<class 'bytes'>
<class 'str'>
ID:4A622E29
卡中塊24數(shù)據(jù)為:1*80*

ID:4A622E29 卡中塊24數(shù)據(jù)為:1*80*
80*
<class 'str'> <class 'str'>

串口助手完整代碼如下:

#coding=gb18030

import threading
import time
import serial

class ComThread:
 def __init__(self, Port='COM3'):
  self.l_serial = None
  self.alive = False
  self.waitEnd = None
  self.port = Port
  self.ID = None
  self.data = None

 def waiting(self):
  if not self.waitEnd is None:
   self.waitEnd.wait()

 def SetStopEvent(self):
  if not self.waitEnd is None:
   self.waitEnd.set()
  self.alive = False
  self.stop()

 def start(self):
  self.l_serial = serial.Serial()
  self.l_serial.port = self.port
  self.l_serial.baudrate = 115200
  self.l_serial.timeout = 2
  self.l_serial.open()
  if self.l_serial.isOpen():
   self.waitEnd = threading.Event()
   self.alive = True
   self.thread_read = None
   self.thread_read = threading.Thread(target=self.FirstReader)
   self.thread_read.setDaemon(1)
   self.thread_read.start()
   return True
  else:
   return False

 def SendDate(self,i_msg,send):
  lmsg = ''
  isOK = False
  if isinstance(i_msg):
   lmsg = i_msg.encode('gb18030')
  else:
   lmsg = i_msg
  try:
   # 發(fā)送數(shù)據(jù)到相應(yīng)的處理組件
   self.l_serial.write(send)
  except Exception as ex:
   pass;
  return isOK

 def FirstReader(self):
  while self.alive:
   time.sleep(0.1)

   data = ''
   data = data.encode('utf-8')

   n = self.l_serial.inWaiting()
   if n:
     data = data + self.l_serial.read(n)
     print('get data from serial port:', data)
     print(type(data))

   n = self.l_serial.inWaiting()
   if len(data)>0 and n==0:
    try:
     temp = data.decode('gb18030')
     print(type(temp))
     print(temp)
     car,temp = str(temp).split("\n",1)
     print(car,temp)

     string = str(temp).strip().split(":")[1]
     str_ID,str_data = str(string).split("*",1)

     print(str_ID)
     print(str_data)
     print(type(str_ID),type(str_data))

     if str_data[-1]== '*':
      break
     else:
      print(str_data[-1])
      print('str_data[-1]!=*')
    except:
     print("讀卡錯誤,請重試!\n")

  self.ID = str_ID
  self.data = str_data[0:-1]
  self.waitEnd.set()
  self.alive = False

 def stop(self):
  self.alive = False
  self.thread_read.join()
  if self.l_serial.isOpen():
   self.l_serial.close()
#調(diào)用串口,測試串口
def main():
 rt = ComThread()
 rt.sendport = '**1*80*'
 try:
  if rt.start():
   print(rt.l_serial.name)
   rt.waiting()
   print("The data is:%s,The Id is:%s"%(rt.data,rt.ID))
   rt.stop()
  else:
   pass
 except Exception as se:
  print(str(se))

 if rt.alive:
  rt.stop()

 print('')
 print ('End OK .')
 temp_ID=rt.ID
 temp_data=rt.data
 del rt
 return temp_ID,temp_data


if __name__ == '__main__':

 #設(shè)置一個主函數(shù),用來運行窗口,便于若其他地方下需要調(diào)用串口是可以直接調(diào)用main函數(shù)
 ID,data = main()

 print("******")
 print(ID,data)

以上這篇對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 手把手教你使用Python創(chuàng)建微信機器人

    手把手教你使用Python創(chuàng)建微信機器人

    微信,一個日活10億的超級app,不僅在國內(nèi)社交獨領(lǐng)風(fēng)騷,在國外社交也同樣占有一席之地,今天我們要將便是如何用Python來生成一個微信機器人,感興趣的朋友跟隨小編一起看看吧
    2019-04-04
  • Python如何使用字符打印照片

    Python如何使用字符打印照片

    這篇文章主要介紹了Python如何使用字符打印照片,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • Pandas過濾dataframe中包含特定字符串的數(shù)據(jù)方法

    Pandas過濾dataframe中包含特定字符串的數(shù)據(jù)方法

    今天小編就為大家分享一篇Pandas過濾dataframe中包含特定字符串的數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Python自動化實戰(zhàn)之接口請求的實現(xiàn)

    Python自動化實戰(zhàn)之接口請求的實現(xiàn)

    本文為大家重點介紹如何通過 python 編碼來實現(xiàn)我們的接口測試以及通過Pycharm的實際應(yīng)用編寫一個簡單接口測試,感興趣的可以了解一下
    2022-05-05
  • python?requests模塊封裝詳解

    python?requests模塊封裝詳解

    requests是一個常用的HTTP請求庫,可以方便地向網(wǎng)站發(fā)送HTTP請求,并獲取響應(yīng)結(jié)果,本文主要和大家介紹一下requests模塊的使用與封裝,需要的可以參考下
    2023-09-09
  • 詳談tensorflow gfile文件的用法

    詳談tensorflow gfile文件的用法

    今天小編就為大家分享一篇詳談tensorflow gfile文件的用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python如何實現(xiàn)convolution neural network卷積神經(jīng)網(wǎng)絡(luò)算法

    python如何實現(xiàn)convolution neural network卷積神經(jīng)網(wǎng)絡(luò)算法

    卷積神經(jīng)網(wǎng)絡(luò)(CNN)是深度學(xué)習(xí)中重要的算法之一,主要應(yīng)用于圖像識別和處理領(lǐng)域,其基本原理是模擬人類視覺系統(tǒng),通過卷積層、激活函數(shù)和池化層等組件提取圖像的特征,并通過全連接層進行分類或其他任務(wù),CNN訓(xùn)練過程中使用大量標記圖像數(shù)據(jù)
    2024-10-10
  • pytorch和numpy默認浮點類型位數(shù)詳解

    pytorch和numpy默認浮點類型位數(shù)詳解

    這篇文章主要介紹了pytorch和numpy默認浮點類型位數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Python繪圖之在父組件中使用子組件的函數(shù)詳解

    Python繪圖之在父組件中使用子組件的函數(shù)詳解

    這篇文章主要為大家詳細介紹了Python在項目開發(fā)時,如何實現(xiàn)在父組件中使用子組件的函數(shù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-08-08
  • Pandas div()函數(shù)的具體使用

    Pandas div()函數(shù)的具體使用

    本文主要介紹了Pandas div()函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03

最新評論

南和县| 宝兴县| 太谷县| 平阴县| 谢通门县| 丰县| 吉隆县| 共和县| 翁源县| 阳山县| 诏安县| 布拖县| 烟台市| 房产| 高雄县| 靖西县| 郑州市| 延吉市| 定边县| 南城县| 卓资县| 阳春市| 道真| 镇平县| 双江| 徐闻县| 甘孜| 博兴县| 册亨县| 运城市| 河源市| 灵武市| 内丘县| 深州市| 永泰县| 丹棱县| 武定县| 溧阳市| 萝北县| 杭锦后旗| 太原市|