1. 程式人生 > >python的pyserial模組

python的pyserial模組

pyserial是python提供用於進行串列埠通訊的庫

源文件:https://pythonhosted.org/pyserial/

1、安裝pyserial

pip install pyserial

2、檢視電腦現連串列埠裝置

import serial.tools.list_ports

#檢測裝置的埠數
# plist = list(serial.tools.list_ports.comports())

# if len(plist) <= 0:
#     print("沒有發現埠!")
# else:
#     #埠數
#     print len(plist)

#     plist_0 = list(plist[1])
#     serialName = plist_0[0]
#     print serialName

#     serialFd = serial.Serial(serialName, 9600, timeout=60)
#     print(serialFd.name)

3、將要傳送的資料進行轉換

所發十六進位制需轉換為以下格式
# 所發十六進位制字串010591F50000F104
cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]
    # 轉成16進位制的函式
    def convert_hex(string, strip_index_end=18):
        result = []
        for i in range(0, strip_index_end, 2):
            hex_num = '0x' + string[i] + string[i+1]
            result.append(eval(hex_num))
        return result

4、進行串列埠通訊

串列埠通訊 
Windows下埠為COM*, Ubuntu下為/dev/ttyS*

class Ser(object):
        def __init__(self):
                # 開啟埠
                self.port = serial.Serial(port=serialconf.SERIAL_NAME, baudrate=serialconf.SERIAL_PORT, timeout=serialconf.SERIAL_TIMEOUT)

    # 傳送指令的完整流程
    def send_cmd(self, send_cmd):
            send_cmd = self.convert_hex(send_cmd)
            _LOG.debug("serial port send_command:[%s]" % repr(send_cmd))
            self.port.write(send_cmd)

    def recv_data(self, len=4):
            response = self.port.read(6)
            response = response.encode('hex')
            return response

    # 轉成16進位制的函式
    def convert_hex(self, string, strip_index_end=18):
            result = []
            for i in range(0, strip_index_end, 2):
                    hex_num = '0x' + string[i] + string[i+1]
                    result.append(eval(hex_num))
            return result

5、測試用例

my_ser = Ser()
print "send blink command"
my_ser.send_cmd(serialconf.BLINK_CMD)
ret = my_ser.recv_data()
print "send blink ret:%s %d" % (ret, ret.lower() == serialconf.BLINK_RET.lower())

6、介面、引數詳細介紹

優秀部落格:https://blog.csdn.net/u012611644/article/details/79125234