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);
}
/********LED  IO口配置***********/
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闪烁表示系统正常运行
 }
}

在这里插入图片描述
以上代码我是亲测可用的。
参考:https://blog.csdn.net/qq_25939803/article/details/104962112 。

发布了469 篇原创文章 · 获赞 742 · 访问量 102万+

猜你喜欢

转载自blog.csdn.net/mao_hui_fei/article/details/105154716