需求描述:
– 平台环境:windows
通过串口编程实现自动化任务(基于python)需要用到的工具:
– python3.7.1(或其他版本)
serial(这是一个让python能收发串口消息的模块)
sublimetext3(或其他代码编辑器)
一、安装python
这里就不详细描述了,python安装网上很多教程(或者完全不需要教程)
附python官方下载地址:https://www.python.org/downloads/
需要注意的是,安装时记得同时安装pip
二、安装serial
这里通过pip进行安装,在命令行下执行pip install pyserial
即可
三、python编程
这是一个扫描当前串口并打印、通过COM5发送AT并打印返回值的Demo,大家可以按需修改,部分代码来自找茬官Jone
#coding:utf-8
#!usr/bin/python3.6
import serial
import sys
import time
import filecmp
import serial.tools.list_ports
#global MAX_LOOP_NUM
#global newCmd
#global sbuf
#sbuf=''
#MAX_LOOP_NUM = 10
def sendInfo(strInfo):
try:
print ('['+time.strftime("%Y-%m-%d %X")+']发→◇'+strInfo.decode())
except Exception:
print ('['+time.strftime("%Y-%m-%d %X")+']发→◇', end='')
print(strInfo)
def recvInfo(strInfo):
try:
print ('['+time.strftime("%Y-%m-%d %X")+']收←◆'+strInfo.decode())
except Exception:
print ('['+time.strftime("%Y-%m-%d %X")+']收←◆', end='')
print(strInfo)
def list_comport():
plist = list(serial.tools.list_ports.comports())
if len(plist) <= 0:
print("没有发现端口!")
else:
for aport in plist:#循环获取所有端口
print("可用端口名>>>",aport[0],"-",aport)
#print(aport)
plist_0 = list(plist[0])
serialName = plist_0[0]
try:
serialFd = serial.Serial(serialName, 9600, timeout=60)
print("可用端口名>>>", serialFd.name)
return serialFd.name
except:
print('无法打开串口')
sys.exit(0)
def waitForCmdOKRsp(timeout):
#maxloopNum = 0
timeout *=10
#print("Rsponse :")
while True:
n=ser.inWaiting()
if n:
line = ser.read(n)
recvInfo(line.decode())
# maxloopNum = maxloopNum + 1
i=line.find(b'OK')
if i>=0:
#print('find ok')
break
time.sleep(0.1)
timeout-=1
if (timeout<=0):
print('[INFO]等待AT命令返回OK超时')
sys.exit(0)
def waitForCmdRsp(timeout):
#maxloopNum = 0
timeout *=10
#print("Rsponse :")
while True:
n=ser.inWaiting()
if n:
line = ser.read(n).decode()
recvInfo(line)
return
# maxloopNum = maxloopNum + 1
time.sleep(0.1)
timeout-=1
if(timeout<=0):
print('[INFO]等待AT命令返回超时')
break
def sendAT_Cmd(serInstance,atCmdStr,waitforOk,timeout):
#print("SendCmd: %s" % atCmdStr)
sendInfo(atCmdStr)
serInstance.write(atCmdStr.encode('utf-8'))
#or define b'string',bytes should be used not str
if(waitforOk == 1):
waitForCmdOKRsp(timeout)
else:
waitForCmdRsp(timeout)
def scanport():#扫描设备端口
plist = list(serial.tools.list_ports.comports())
if len(plist) <= 0:
print("没有发现端口!")
else:
for aport in plist:#循环获取所有端口
print("可用端口名>>>",aport)
#print(aport)
return plist
portlist = scanport()
for a in portlist:
print(a)
comport='COM5'#设置AT端口
try:
ser = serial.Serial(port=comport, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0)
if ser.isOpen() :
print("[INFO]%s open success" % comport)
else :
print("[INFO]%s open failed" % comport)
except:
print ("[INFO]请查看是否成功打开设备端口:"+comport)
sys.exit()
sendAT_Cmd(ser,'AT\r\n',1, 5)
示例运行截图: