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

在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("\r\n %.3f",value*3.3/4096);	
//在Windows中 \r\n 才是回车

此外:
在这里插入图片描述

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

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值