美文网首页
2018-08-31 uart通信

2018-08-31 uart通信

作者: 清亮2015 | 来源:发表于2018-08-31 20:23 被阅读0次

    usart通信

    第一步

    串口通行设置

    void uart_init(void)
    {
    //定时一个该结构体
        GPIO_InitTypeDef GPIO_InitStructure;
        USART_InitTypeDef USART_InitStructure;
        NVIC_InitTypeDef   NVIC_InitStructure;
        
        // 使能时钟
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
        RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
        
        // 设置PF9为复用
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
        GPIO_Init(GPIOA, &GPIO_InitStructure); 
    
        //由于使用到PF9的复用功能,利用库函数使其引脚与TIM14定时器绑定
        GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1); 
        GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1); 
        
    
        // 初始化串口
        USART_InitStructure.USART_BaudRate = 115200; // 波特率
        USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; // 无硬件流控
        USART_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx; // 设置收发模式
        USART_InitStructure.USART_Parity = USART_Parity_No;  // 无奇偶校验位
        USART_InitStructure.USART_StopBits = USART_StopBits_1; //一个停止位
        USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长为 8 位数据格式
    
        USART_Init(USART1, &USART_InitStructure);
        
        // 使能串口1
        USART_Cmd(USART1, ENABLE);
    
        // 开启串口中断--》 接收             // USART_IT_RXNE
        USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); 
        
        // 初始化NVIC
        NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //设置中断通道
      NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x03; // 设置抢占优先级
      NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x03;  // 设置响应优先级
      NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // 使能
      NVIC_Init(&NVIC_InitStructure);
    
    }
    

    中断服务函数

    void USART1_IRQHandler(void)
    {
        
        while(1)
        {
        if(USART_GetITStatus(USART1, USART_IT_RXNE) == SET)//判断中断是否被执行
        {
            res = USART_ReceiveData(USART1);//接收数据
            USART_SendData(USART1, res);//发送数据
            if(res == '\n')
            break;
        }
    }
    

    最终实现功能:

    是在串口助手上获取数据打印数据。

    相关文章

      网友评论

          本文标题:2018-08-31 uart通信

          本文链接:https://www.haomeiwen.com/subject/rzuewftx.html