V853 发表于 2022-9-13 13:39

Python与STM32F103串口通讯

serial库安装pip install pyserial

python上位机代码
以下功能具体封装成函数了,在实际开发中,接收数据可以和线程配合使用。实现了循环发送与接收
import serial

# 串口打开函数
def open_ser():
    port = 'com5'# 串口号
    baudrate = 9600# 波特率
    try:
      global ser
      ser = serial.Serial(port,baudrate,timeout=2)
      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)
      send_datas1=875
      ser.write(str(send_datas1).encode("gbk"))
      print("已发送数据:",send_datas1)
    except Exception as exc:
      print("发送异常", exc)
      
# 接收数据
def read_msg():
    try:
      print("等待接收数据")
      while True:
            data = ser.read(ser.in_waiting).decode('gbk')
            if data != '':
                break
      print("已接受到数据:",data)
    except Exception as exc:
      print("读取异常",exc)
      
# 关闭串口
def close_ser():
      try:
            ser.close()
            if ser.isOpen():
                print("串口未关闭")
            else:
                print("串口已关闭")
      except Exception as exc:
            print("串口关闭异常", exc)
            
if __name__ == '__main__':
    open_ser()   # 打开串口
    while 1:
      send_msg()   # 写数据
      read_msg()   # 读数据
    close_ser()# 关闭串口
stm32端程序
在这里32 的程序没必要太复杂,就写一个串口程序方便测试就行。
以下的32 串口程序的功能是:将接受到的数据原封不动的发送回去。
led的功能只是一个指示功能,表示32系统正常运行。

#include <stm32f10x.h>
#include <SysTick.h>

void USART1_Init(u32 bound)
{
   //端口设置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
/*配置IO口*/
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//TX PA9
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;   
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;//RX PA10
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;   
GPIO_Init(GPIOA,&GPIO_InitStructure);
   //USART1 初始化设置
USART_InitStructure.USART_BaudRate = bound;//波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
USART_ClearFlag(USART1, USART_FLAG_TC);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启相关中断
//Usart1 NVIC 中断配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;//串口1中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;//抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority =3;//子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
/*********中断服务子程序************/
void USART1_IRQHandler(void)               
{
unsigned char r;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
r =USART_ReceiveData(USART1);//(USART1->DR);
USART_SendData(USART1,r);
while(USART_GetFlagStatus(USART1,USART_FLAG_TC) != SET);
}
USART_ClearFlag(USART1,USART_FLAG_TC);
}
/********LEDIO口配置***********/
void LED_INIT()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_13;//PC13
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;   
GPIO_Init(GPIOC,&GPIO_InitStructure);
GPIO_SetBits(GPIOC,GPIO_Pin_13);
}
/**************LED闪烁***************/
void display1(void)
{
GPIO_SetBits(GPIOC,GPIO_Pin_13);//点亮         
delay_ms(1000);
GPIO_ResetBits(GPIOC,GPIO_Pin_13);//熄灭         
delay_ms(1000);
}
/***********主函数**************/
int main()
{
SysTick_Init(72);   
LED_INIT();      //led初始化
USART1_Init(9600);//串口初始化,自动开启串口中断,进行数据自动接收和发送
while(1)
{
display1();// led闪烁表示系统正常运行
}
}


一枝香 发表于 2022-11-26 23:20

Python也能做上位机啊?挺好玩啊

占得人间第一春 发表于 2022-11-26 23:52

这python用的是啥开发环境?

可爱的白兔先生 发表于 2022-11-27 00:24

现在好像用python写脚本的比较多,再弄弄数据处理之类的

偷吻月亮 发表于 2022-11-27 00:56

感觉挺不错的,就这点儿代码就能实现这个功能

热爱童话世界 发表于 2022-11-27 01:28

STM32串口还是比较简单而且好用的

喜爱弄人 发表于 2022-11-27 02:00

楼主可以试试cubemx,做底层搭建的话,更快

地下縱情搖擺 发表于 2022-11-27 02:32

自己写串口上位机挺好,可以拓展拓展,丰富一下上位机工具

林间有新绿 发表于 2022-11-27 03:04

话说,python的话,开发起来简单么?

情和欲 发表于 2022-11-27 03:36

这种语言一般需要掌握什么啊?就脚本语言就行么?

极客晨星 发表于 2022-11-27 04:08

根据这个python写的串口助手比较简单啊,没用多少代码就实现了

V853 发表于 2022-12-3 20:23

一枝香 发表于 2022-11-26 23:20
Python也能做上位机啊?挺好玩啊

对啊,Python可以做的东西非常多的。

V853 发表于 2022-12-3 20:25

占得人间第一春 发表于 2022-11-26 23:52
这python用的是啥开发环境?

PyCharm,这个是专门用于Python开发的。

V853 发表于 2022-12-3 20:26

可爱的白兔先生 发表于 2022-11-27 00:24
现在好像用python写脚本的比较多,再弄弄数据处理之类的

对的,还有机器学习哦!

V853 发表于 2022-12-3 20:26

林间有新绿 发表于 2022-11-27 03:04
话说,python的话,开发起来简单么?

非常简单,小学生都可以上手开发的一个开发语言!

V853 发表于 2022-12-3 20:27

情和欲 发表于 2022-11-27 03:36
这种语言一般需要掌握什么啊?就脚本语言就行么?

Python就是一种语言,只要会用它的库就行。

V853 发表于 2022-12-3 20:28

地下縱情搖擺 发表于 2022-11-27 02:32
自己写串口上位机挺好,可以拓展拓展,丰富一下上位机工具

对的,主要可以做调试工具用!

Wordsworth 发表于 2024-11-4 07:05


从定时器为TIM2,从模式选择为门控模式,触发源选择ITR0,开启定时器2中断。

Clyde011 发表于 2024-11-4 08:08


根据实际需求选择用哪种方式

公羊子丹 发表于 2024-11-4 09:01


每条大电流的地线要短而宽
页: [1]
查看完整版本: Python与STM32F103串口通讯