串口打印数据输出

本文介绍了在MDK环境中如何正确使用printf函数进行输出。包括配置步骤、避免使用半主机模式的方法以及自定义输出函数的实现。此外还提供了一种完全不依赖库函数的输出方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用MDK的情况

1.使用printf库函数时,要加入头文件<stdio.h>

2.另外在keil里面需要把:use MicroLIB 勾选上,不然程序没办法在线调试。编译的时候不会报错。

3.当然可以不用库函数,自己写。正点原子里面的代码:

 //加入以下代码,支持printf函数,而不需要选择use MicroLIB

#if 1
 #pragma import(__use_no_semihosting) 
 //标准库需要的支持函数 
struct __FILE 
{ 
  int handle;

};

FILE __stdout; 
//定义_sys_exit()以避免使用半主机模式 
_sys_exit(int x) 
{ 
  x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{ 
  while((USART1->SR&0X40)==0);//循环发送,直到发送完毕 
  USART1->DR = (u8) ch; 
  return ch;
}
#endif


/*使用microLib的方法*/

/* 
int fputc(int ch, FILE *f)
{
  USART_SendData(USART1, (uint8_t) ch);

  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {}	
  return ch;
}
int GetKey (void)

{

  while (!(USART1->SR & USART_FLAG_RXNE));

  return ((int)(USART1->DR & 0x1FF));
}
*/


不使用printf 自己使用vsprint函数

#include <stdarg.h>

uint8_t g_uartPrintStr[256];
void shellPrint(const char *fmt, ...)
{
    va_list ap;
    int i;
	
    va_start(ap, fmt);
    vsprintf((char *)g_uartPrintStr, fmt, ap);
	
    va_end(ap);


    for (i = 0; i < 128; i++)
    {
        if (g_uartPrintStr[i] == '\0')
        {
             break;
        }
    }


    shellSnd((uint8_t *)g_uartPrintStr , i);
}


再增加一个:

/*******************************************************************************
* Function Name  : int fputc(int ch, FILE *f)
* Description    : Retargets the C library printf function to the USART.printfÖØ¶¨Ïò
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
//int fputc(int ch, FILE *f)
//{
//  UART_SendByte(UART_0, (uint8_t) ch); /* Write a character to the USART */
//  while((LPC_UART0->LSR&0x40)==0){}; /* Loop until the end of transmission */
//  return ch;
//}

/*******************************************************************************
* Function Name  : int fgetc(FILE *f)
* Description    : Retargets the C library printf function to the USART.fgetcÖØ¶¨Ïò
* Input          : None
* Output         : None
* Return         : Read a character from the USART
*******************************************************************************/
//int fgetc(FILE *f)
//{
//  while((LPC_UART0->LSR&0x1)==0){};//* Loop until received a char */
//  return (UART_ReceiveByte(UART_0));/* Read a character from the USART and RETURN */
//}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值