• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

使用Python和Stm32进行通信

武飞扬头像
def__init__1923
帮助1

方法:利用python的serial函数库与STM32进行通信。

将Stm32用USB连接到电脑,打开设备管理器查看端口,端口为COM3。

写下Python程序:

  1.  
    import serial
  2.  
     
  3.  
    # 连接串口
  4.  
    serial = serial.Serial('COM3', 9600, timeout=0.1)
  5.  
    if serial.isOpen():
  6.  
    print('串口已打开')
  7.  
     
  8.  
    data = b'Hello STM32!!!\r\n' # 发送的数据
  9.  
    serial.write(data) # 串口写数据
  10.  
    print("-" * 40)
  11.  
    print('Python Send :\n', data)
  12.  
    print("-" * 40)
  13.  
    while True:
  14.  
    data = serial.read_all()
  15.  
    if data != b'':
  16.  
    break
  17.  
    print("-" * 40)
  18.  
    print('STM32 Send :\n', data.decode("GBK"))
  19.  
    print("-" * 40)
  20.  
    else:
  21.  
    print('串口未打开')
  22.  
     
  23.  
    # 关闭串口
  24.  
    serial.close()
  25.  
     
  26.  
    if serial.isOpen():
  27.  
    print('串口未关闭')
  28.  
    else:
  29.  
    print('串口已关闭')
学新通

写下Stm32程序(使用正点原子例程):

  1.  
    int main(void)
  2.  
    {
  3.  
    u16 t;
  4.  
    u16 len;
  5.  
    u16 times=0;
  6.  
    delay_init(); //延时函数初始化
  7.  
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
  8.  
    uart_init(9600); //串口初始化为115200
  9.  
    LED_Init(); //LED端口初始化
  10.  
    KEY_Init(); //初始化与按键连接的硬件接口
  11.  
    while(1)
  12.  
    {
  13.  
    if(USART_RX_STA&0x8000)
  14.  
    {
  15.  
    len=USART_RX_STA&0x3fff;//得到此次接收到的数据长度
  16.  
     
  17.  
    printf("你发送的消息是:\r\n");
  18.  
     
  19.  
    for(t=0;t<len;t )
  20.  
    {
  21.  
    USART_SendData(USART1, USART_RX_BUF[t]);//向串口1发送数据
  22.  
    while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//等待发送结束
  23.  
    }
  24.  
    printf("\r\n\r\n");//插入换行
  25.  
    USART_RX_STA=0;
  26.  
    }else
  27.  
    {
  28.  
    times ;
  29.  
    /*
  30.  
    if(timesP00==0)
  31.  
    {
  32.  
    printf("精英STM32开发板 串口实验\r\n");
  33.  
    printf("正点原子@ALIENTEK\r\n\r\n");
  34.  
    }
  35.  
    if(times 0==0)printf("\r\n请输入数据,以回车键结束\r\n"); */
  36.  
    if(times%100==0)LED0=!LED0;//闪烁LED,提示系统正在运行.
  37.  
     
  38.  
    delay_ms(10);
  39.  
    }
  40.  
    }
  41.  
    }
学新通

115200波特率在发送时不是特别稳定,所以将波特率设为9600。

查看结果:

学新通

timeout可以自己设置,比如将timeout设为0.1秒,然后read_all时就会读取0.1秒内串口接收的全部消息。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhaebfa
系列文章
更多 icon
同类精品
更多 icon
继续加载