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

[复制链接]
3327|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的函数如下:
  1. void USART1_Config(void)
  2. {
  3.         GPIO_InitTypeDef GPIO_InitStructure;
  4.         USART_InitTypeDef USART_InitStructure;
  5.        
  6.         /* config USART1 clock */
  7.         RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
  8.        
  9.         /* USART1 GPIO config */
  10.         /* Configure USART1 Tx (PA.09) as alternate function push-pull */
  11.         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  12.         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  13.         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  14.         GPIO_Init(GPIOA, &GPIO_InitStructure);   
  15.         /* Configure USART1 Rx (PA.10) as input floating */
  16.         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  17.         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  18.         GPIO_Init(GPIOA, &GPIO_InitStructure);
  19.           
  20.         /* USART1 mode config */
  21.         USART_InitStructure.USART_BaudRate = 115200;
  22.         USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  23.         USART_InitStructure.USART_StopBits = USART_StopBits_1;
  24.         USART_InitStructure.USART_Parity = USART_Parity_No ;
  25.         USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  26.         USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  27.         USART_Init(USART1, &USART_InitStructure);
  28.         USART_Cmd(USART1, ENABLE);
  29. }
 楼主| sunmeat 发表于 2014-9-26 15:26 | 显示全部楼层
重定向的函数如下:
  1. /*
  2. * 函数名:fputc
  3. * 描述  :重定向c库函数printf到USART1
  4. * 输入  :无
  5. * 输出  :无
  6. * 调用  :由printf调用
  7. */
  8. int fputc(int ch, FILE *f)
  9. {
  10.         /* 将Printf内容发往串口 */
  11.         USART_SendData(USART1, (unsigned char) ch);
  12. //        while (!(USART1->SR & USART_FLAG_TXE));
  13.         while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);       
  14.         return (ch);
  15. }
您需要登录后才可以回帖 登录 | 注册

本版积分规则

208

主题

2132

帖子

13

粉丝
快速回复 在线客服 返回列表 返回顶部