pyserial是python提供用于进行串口通信的库h5> 源文档:https://pythonhosted.org/pyserial/
1,安装pyserial
<代码> pip安装pyserial 代码>
2,查看电脑现连串口设备
<代码>进口serial.tools.list_ports
#检测设备的端口数
# plist=列表(serial.tools.list_ports.comports ())
#如果len (plist) & lt;=0:
#打印(“没有发现端口!”)
其他:
# #端口数
#打印len (plist)
# plist_0=列表(plist [1])
# serialName=plist_0 [0]
#打印serialName
# serialFd=系列。系列(9600年serialName超时=60)
#打印(serialFd.name) 代码>
将 3日要发送的数据进行转换
<代码>所发十六进制需转换为以下格式
#所发十六进制字符串010591 f50000f104
cmd=[0 x01 0 x05 0 x91, 0 xf5 0 x00, 0 x00, 0 xf1 0 x04] 代码>
<代码> #转成16进制的函数
def convert_hex(字符串,strip_index_end=18):
结果=[]
因为我在范围(0 strip_index_end 2):
hex_num=' 0 x +字符串[我]+字符串(i + 1)
result.append (eval (hex_num))
返回结果代码> >之前
4,进行串口通信
<代码>串口通信
Windows下端口为COM *, Ubuntu下为/dev/tty *
类Ser(对象):
def __init__(自我):
#打开端口
自我。端口=serial.Serial (=serialconf港。SERIAL_NAME,波特率=serialconf。SERIAL_PORT,超时=serialconf.SERIAL_TIMEOUT)
#发送指令的完整流程
def send_cmd(自我,send_cmd):
send_cmd=self.convert_hex (send_cmd)
_LOG.debug(“串口send_command: [% s]”% repr (send_cmd))
self.port.write (send_cmd)
def recv_data(自我,len=4):
响应=self.port.read (6)
响应=response.encode(十六进制)
返回响应
#转成16进制的函数
def convert_hex(自我,字符串,strip_index_end=18):
结果=[]
因为我在范围(0 strip_index_end 2):
hex_num=' 0 x +字符串[我]+字符串(i + 1)
result.append (eval (hex_num))
返回结果代码> >之前
5,测试用例
<代码> my_ser=Ser ()
打印“发送眨眼命令”
my_ser.send_cmd (serialconf.BLINK_CMD)
ret=my_ser.recv_data ()
打印”发送眨眼ret: % s % d % (ret, ret.lower ()==serialconf.BLINK_RET.lower()) 代码>
6,接口,参数详细介绍
<代码>优秀博客:https://blog.csdn.net/u012611644/article/details/79125234 代码>
python的pyserial模块
4,进行串口通信
<代码>串口通信 Windows下端口为COM *, Ubuntu下为/dev/tty * 类Ser(对象): def __init__(自我): #打开端口 自我。端口=serial.Serial (=serialconf港。SERIAL_NAME,波特率=serialconf。SERIAL_PORT,超时=serialconf.SERIAL_TIMEOUT) #发送指令的完整流程 def send_cmd(自我,send_cmd): send_cmd=self.convert_hex (send_cmd) _LOG.debug(“串口send_command: [% s]”% repr (send_cmd)) self.port.write (send_cmd) def recv_data(自我,len=4): 响应=self.port.read (6) 响应=response.encode(十六进制) 返回响应 #转成16进制的函数 def convert_hex(自我,字符串,strip_index_end=18): 结果=[] 因为我在范围(0 strip_index_end 2): hex_num=' 0 x +字符串[我]+字符串(i + 1) result.append (eval (hex_num)) 返回结果代码> >之前5,测试用例
<代码> my_ser=Ser () 打印“发送眨眼命令” my_ser.send_cmd (serialconf.BLINK_CMD) ret=my_ser.recv_data () 打印”发送眨眼ret: % s % d % (ret, ret.lower ()==serialconf.BLINK_RET.lower()) 代码>6,接口,参数详细介绍
<代码>优秀博客:https://blog.csdn.net/u012611644/article/details/79125234 代码>python的pyserial模块