在HAL库中的使用printf()函数和sprintf()函数


运行环境为:HAL库。

1.printf();

如果想要在串口中使用printf函数,就需要将这个函数重定向。

#ifdef __GNUC__
  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
     set to Yes) calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
          
   
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART */
	huart1.Instance->DR = (uint8_t) ch;
 
  /* Loop until the end of transmission */
	while(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_TC) == RESET){
          
   }
 
  return ch;
}

调用实例:

#include <stdio.h>
unsigned int value=3000;//12位ADC的值

printf("
 %.3f",value*3.3/4096);	
//在Windows中 
 才是回车

此外:

2.sprintf():

C 库 : int sprintf(char *str, const char *format, …)

str:指向 格式转换完后存储的 字符数组的指针 format:%[flags][width][.precision][length]specifier

调用实例:

#include <stdio.h>
char TxData[10]={
          
   0};
unsigned int value=3000;//12位ADC的值

sprintf(TxData,"%.3f",value*3.3/4096);
HAL_UART_Transmit(&huart1,(unsigned char *)TxData,5,0xffff);
//(unsigned char*)是强制转换 无符号的指针类型。
//相反,(char*)是强制转换 有符号的指针类型。如果大于127即0x7F的数就是负数了,使用%x格式化输出,系统自动进行了符号扩展。

输出: 2.417

经验分享 程序员 微信小程序 职场和发展