打印

GD32使用printf函数定向UART输出的说明

[复制链接]
2870|4
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
sunmeat|  楼主 | 2014-9-26 12:07 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 sunmeat 于 2014-9-26 18:45 编辑

本人是从新唐的M0转过来的,一直以为M3也可以半主机打印,照着网上的说法弄了半天,怎么没反应呢,弄了好久才搞明白M3 printf()使用的情况。

沙发
sunmeat|  楼主 | 2014-9-26 14:22 | 只看该作者
M3的printf其实还是使用的串口,不是半主机,只不过是借用了经典的printf函数,发送字符串的时候,使用了printf函数而已,因此需要把printf()重新定向到串口。

使用特权

评论回复
板凳
sunmeat|  楼主 | 2014-9-26 15:25 | 只看该作者
因此,在使用printf之前,需要先配置UART1,因为重定向中用到的就是串口1.

使用特权

评论回复
地板
sunmeat|  楼主 | 2014-9-26 15:25 | 只看该作者
配置串口1的函数如下:
void USART1_Config(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;
        USART_InitTypeDef USART_InitStructure;
       
        /* config USART1 clock */
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
       
        /* USART1 GPIO config */
        /* Configure USART1 Tx (PA.09) as alternate function push-pull */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_Init(GPIOA, &GPIO_InitStructure);   
        /* Configure USART1 Rx (PA.10) as input floating */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
          
        /* USART1 mode config */
        USART_InitStructure.USART_BaudRate = 115200;
        USART_InitStructure.USART_WordLength = USART_WordLength_8b;
        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);
}

使用特权

评论回复
5
sunmeat|  楼主 | 2014-9-26 15:26 | 只看该作者
重定向的函数如下:
/*
* 函数名:fputc
* 描述  :重定向c库函数printf到USART1
* 输入  :无
* 输出  :无
* 调用  :由printf调用
*/
int fputc(int ch, FILE *f)
{
        /* 将Printf内容发往串口 */
        USART_SendData(USART1, (unsigned char) ch);
//        while (!(USART1->SR & USART_FLAG_TXE));
        while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);       
        return (ch);
}

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

208

主题

2132

帖子

13

粉丝