Python 官方文档:入门教程 => 点击学习
pyserial是python提供用于进行串口通信的库 源文档:https://Pythonhosted.org/pyserial/ 1、安装pyserial pip install pyserial 2、查看电脑现连串口设备 import
pip install pyserial
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)
所发十六进制需转换为以下格式
# 所发十六进制字符串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
串口通信
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
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())
优秀博客:Https://blog.csdn.net/u012611644/article/details/79125234
--结束END--
本文标题: python的pyserial模块
本文链接: https://lsjlt.com/news/191303.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0