溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python實(shí)現(xiàn)串口通信的方法

發(fā)布時(shí)間:2021-04-06 10:32:43 來(lái)源:億速云 閱讀:556 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Python實(shí)現(xiàn)串口通信的方法,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

pyserial模塊封裝了對(duì)串口的訪問(wèn),兼容各種平臺(tái)。

安裝

pip insatll pyserial

初始化

簡(jiǎn)單初始化示例

import serial
ser = serial.Serial('com1', 9600, timeout=1)

所有參數(shù)

ser = serial.Serial(
port=None,       # number of device, numbering starts at
# zero. if everything fails, the user
# can specify a device string, note
# that this isn't portable anymore
# if no port is specified an unconfigured
# an closed serial port object is created
baudrate=9600,     # baud rate
bytesize=EIGHTBITS,   # number of databits
parity=PARITY_NONE,   # enable parity checking
stopbits=STOPBITS_ONE, # number of stopbits
timeout=None,      # set a timeout value, None for waiting forever
xonxoff=0,       # enable software flow control
rtscts=0,        # enable RTS/CTS flow control
interCharTimeout=None  # Inter-character timeout, None to disable
)

不同平臺(tái)下初始化

ser=serial.Serial("/dev/ttyUSB0",9600,timeout=0.5) #使用USB連接串行口
ser=serial.Serial("/dev/ttyAMA0",9600,timeout=0.5) #使用樹(shù)莓派的GPIO口連接串行口
ser=serial.Serial(1,9600,timeout=0.5)#winsows系統(tǒng)使用com1口連接串行口
ser=serial.Serial("com1",9600,timeout=0.5)#winsows系統(tǒng)使用com1口連接串行口
ser=serial.Serial("/dev/ttyS1",9600,timeout=0.5)#Linux系統(tǒng)使用com1口連接串行口

serial.Serial類(另外初始化的方法)

class serial.Serial()
{
  def __init__(port=None, baudrate=9600, bytesize=EIGHTBITS,parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=None)
}

ser對(duì)象屬性

name:設(shè)備名字
port:讀或者寫(xiě)端口
baudrate:波特率
bytesize:字節(jié)大小
parity:校驗(yàn)位
stopbits:停止位
timeout:讀超時(shí)設(shè)置
writeTimeout:寫(xiě)超時(shí)
xonxoff:軟件流控
rtscts:硬件流控
dsrdtr:硬件流控
interCharTimeout:字符間隔超時(shí)

ser對(duì)象常用方法

ser.isOpen():查看端口是否被打開(kāi)。
ser.open() :打開(kāi)端口‘。
ser.close():關(guān)閉端口。
ser.read():從端口讀字節(jié)數(shù)據(jù)。默認(rèn)1個(gè)字節(jié)。
ser.read_all():從端口接收全部數(shù)據(jù)。
ser.write("hello"):向端口寫(xiě)數(shù)據(jù)。
ser.readline():讀一行數(shù)據(jù)。
ser.readlines():讀多行數(shù)據(jù)。
in_waiting():返回接收緩存中的字節(jié)數(shù)。
flush():等待所有數(shù)據(jù)寫(xiě)出。
flushInput():丟棄接收緩存中的所有數(shù)據(jù)。
flushOutput():終止當(dāng)前寫(xiě)操作,并丟棄發(fā)送緩存中的數(shù)據(jù)。

封裝參考

import serial
import serial.tools.list_ports

class Communication():

  #初始化
  def __init__(self,com,bps,timeout):
    self.port = com
    self.bps = bps
    self.timeout =timeout
    global Ret
    try:
      # 打開(kāi)串口,并得到串口對(duì)象
       self.main_engine= serial.Serial(self.port,self.bps,timeout=self.timeout)
      # 判斷是否打開(kāi)成功
       if (self.main_engine.is_open):
        Ret = True
    except Exception as e:
      print("---異常---:", e)

  # 打印設(shè)備基本信息
  def Print_Name(self):
    print(self.main_engine.name) #設(shè)備名字
    print(self.main_engine.port)#讀或者寫(xiě)端口
    print(self.main_engine.baudrate)#波特率
    print(self.main_engine.bytesize)#字節(jié)大小
    print(self.main_engine.parity)#校驗(yàn)位
    print(self.main_engine.stopbits)#停止位
    print(self.main_engine.timeout)#讀超時(shí)設(shè)置
    print(self.main_engine.writeTimeout)#寫(xiě)超時(shí)
    print(self.main_engine.xonxoff)#軟件流控
    print(self.main_engine.rtscts)#軟件流控
    print(self.main_engine.dsrdtr)#硬件流控
    print(self.main_engine.interCharTimeout)#字符間隔超時(shí)

  #打開(kāi)串口
  def Open_Engine(self):
    self.main_engine.open()

  #關(guān)閉串口
  def Close_Engine(self):
    self.main_engine.close()
    print(self.main_engine.is_open) # 檢驗(yàn)串口是否打開(kāi)

  # 打印可用串口列表
  @staticmethod
  def Print_Used_Com():
    port_list = list(serial.tools.list_ports.comports())
    print(port_list)





  #接收指定大小的數(shù)據(jù)
  #從串口讀size個(gè)字節(jié)。如果指定超時(shí),則可能在超時(shí)后返回較少的字節(jié);如果沒(méi)有指定超時(shí),則會(huì)一直等到收完指定的字節(jié)數(shù)。
  def Read_Size(self,size):
    return self.main_engine.read(size=size)

  #接收一行數(shù)據(jù)
  # 使用readline()時(shí)應(yīng)該注意:打開(kāi)串口時(shí)應(yīng)該指定超時(shí),否則如果串口沒(méi)有收到新行,則會(huì)一直等待。
  # 如果沒(méi)有超時(shí),readline會(huì)報(bào)異常。
  def Read_Line(self):
    return self.main_engine.readline()

  #發(fā)數(shù)據(jù)
  def Send_data(self,data):
    self.main_engine.write(data)

  #更多示例
  # self.main_engine.write(chr(0x06).encode("utf-8")) # 十六制發(fā)送一個(gè)數(shù)據(jù)
  # print(self.main_engine.read().hex()) # # 十六進(jìn)制的讀取讀一個(gè)字節(jié)
  # print(self.main_engine.read())#讀一個(gè)字節(jié)
  # print(self.main_engine.read(10).decode("gbk"))#讀十個(gè)字節(jié)
  # print(self.main_engine.readline().decode("gbk"))#讀一行
  # print(self.main_engine.readlines())#讀取多行,返回列表,必須匹配超時(shí)(timeout)使用
  # print(self.main_engine.in_waiting)#獲取輸入緩沖區(qū)的剩余字節(jié)數(shù)
  # print(self.main_engine.out_waiting)#獲取輸出緩沖區(qū)的字節(jié)數(shù)
  # print(self.main_engine.readall())#讀取全部字符。

  #接收數(shù)據(jù)
  #一個(gè)整型數(shù)據(jù)占兩個(gè)字節(jié)
  #一個(gè)字符占一個(gè)字節(jié)

  def Recive_data(self,way):
    # 循環(huán)接收數(shù)據(jù),此為死循環(huán),可用線程實(shí)現(xiàn)
    print("開(kāi)始接收數(shù)據(jù):")
    while True:
      try:
        # 一個(gè)字節(jié)一個(gè)字節(jié)的接收
        if self.main_engine.in_waiting:
          if(way == 0):
            for i in range(self.main_engine.in_waiting):
              print("接收ascii數(shù)據(jù):"+str(self.Read_Size(1)))
              data1 = self.Read_Size(1).hex()#轉(zhuǎn)為十六進(jìn)制
              data2 = int(data1,16)#轉(zhuǎn)為十進(jìn)制
              if (data2 == "exit"): # 退出標(biāo)志
                break
              else:
                 print("收到數(shù)據(jù)十六進(jìn)制:"+data1+" 收到數(shù)據(jù)十進(jìn)制:"+str(data2))
          if(way == 1):
            #整體接收
            # data = self.main_engine.read(self.main_engine.in_waiting).decode("utf-8")#方式一
            data = self.main_engine.read_all()#方式二
            if (data == "exit"): # 退出標(biāo)志
              break
            else:
               print("接收ascii數(shù)據(jù):", data)
      except Exception as e:
        print("異常報(bào)錯(cuò):",e)


Communication.Print_Used_Com()
Ret =False #是否創(chuàng)建成功標(biāo)志

Engine1 = Communication("com12",115200,0.5)
if (Ret):
  Engine1.Recive_data(0)
while(1)
  {
   //發(fā)送測(cè)試
   uint8_t a = 61;
   delayms(300);
   printf("%c", a);
}
開(kāi)始接收數(shù)據(jù):
接收ascii數(shù)據(jù):b'='
收到數(shù)據(jù)十六進(jìn)制:3d 收到數(shù)據(jù)十進(jìn)制:61

關(guān)于“Python實(shí)現(xiàn)串口通信的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI