GD32F350 UART

这里试下把 GD32F350 的UART 用起来,把 printf 、uart 中断用起来,实现串口通过 printf 输出数据,通过中断接收实现 echo 功能,没实际用途,所使用代码均来自 GD32F350 SDK 中的例程。

  1. 配置 IO 口,把 PA9、PA10 复用为 UART 的 TX、RX,代码如下:
/*!
    \brief      cofigure the USART0 GPIO ports
    \param[in]  none
    \param[out] none
    \retval     none
*/
void usart0_gpio_config(void)
{
    /* enable COM GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOA);

    /* connect port to USARTx_Tx */
    gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_9);

    /* connect port to USARTx_Rx */
    gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_10);

    /* configure USART Tx as alternate function push-pull */
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_9);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_9);

    /* configure USART Rx as alternate function push-pull */
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_10);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_10);
}
  1. 配置 Usart0,配置波特率,使能发送、接收:
/*!
    \brief      cofigure the USART0
    \param[in]  none
    \param[out] none
    \retval     none
*/
void usart0_config(void)
{
    /* enable USART clock */
    rcu_periph_clock_enable(RCU_USART0);

    /* USART configure */
    usart_deinit(USART0);
    usart_baudrate_set(USART0, 115200U);
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);
    usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);

    usart_enable(USART0);
}
  1. usart0 中断配置:
void usart0_int_init(void)
{
    /* USART interrupt configuration */
    nvic_irq_enable(USART0_IRQn, 0, 0);
    
    usart_interrupt_enable(USART0, USART_INT_RBNE);
}

把上述初始化函数放到一个函数里面:

void usart0_init(void)
{
  usart0_gpio_config();
  usart0_config();
  usart0_int_init();
}
  1. 实现一个发送字符函数,并实现 fputc,这样就可以使用 printf 函数:
void usart0_send_ch(uint8_t ch)
{
    usart_data_transmit(USART0, (uint8_t) ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
}
/* retarget the C library printf function to the USART */
int fputc(int ch, FILE *f)
{
    usart_data_transmit(USART0, (uint8_t) ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    return ch;
}
  1. uart0 中断处理函数:
/*!
    \brief      this function handles USART RBNE interrupt request and TBE interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USART0_IRQHandler(void)
{
  uint16_t re = 0;
    if(RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE)){
        /* receive data */
      re = usart_data_receive(USART0);
      
        if( re == 13)
        {
          usart0_send_ch('\r');
          usart0_send_ch('\n');
        }else
           usart0_send_ch(re);
    }
}

只处理了接收部分,如果接收到了回车(13),返回“\r\n”,否则直接返回接收到的数据,在一个串口终端中运行结果如下:

实现了预想功能,其实这还是有问题,如果输入的不是显示字符,会显示会有些不正常

posted @ 2022-07-04 22:12  哈拎  阅读(433)  评论(0编辑  收藏  举报