文章目录
准备工作
要想用python与stm32通讯,首先就要安装python的相关库—pyserial。
其次准备一块32芯片烧录好串口收发程序准备测试,如果手头没有32的话,下载安装虚拟串口进行调试吧。具体安装方法自行百度。废话就不多说了直接上我的案例程序吧。
Python 上位机程序
以下功能具体封装成函数了,在实际开发中,接收数据可以和线程配合使用。
import serial
# 串口打开函数
def open_ser():
port = 'com4' # 串口号
baudrate = 9600 # 波特率
try:
global ser
ser = serial.Serial(port,baudrate,timeout=0.5)
if(ser.isOpen()==True):
print("串口打开成功")
except Exception as exc:
print("串口打开异常",exc)
# 数据发送
def send_msg():
try:
send_datas = input("请输入要发送的数据\n")
ser.write(str(send_datas).encode("gbk"))
print("已发送数据:",send_datas)
except Exception as exc:
print("发送异常", exc)
# 接收数据
def read_msg():
try:
print("等待接收数据")