摘要
最近stm32一个项目需要用到串口屏,串口WiFi,和调试串口,用hal库提供的API用起来比较繁琐,所以想重定向printf,实现多个串口printf函数,用起来比较方便,所以有了这篇博客。
正题
方法一
用c库的vsnprintf函数,这个函数包含在stdio.h里
extern _ARMABI int __ARM_vsnprintf(char * __restrict , size_t ,
const char * __restrict , __va_list ) __attribute__((__nonnull__(3)));
#if !defined(__STRICT_ANSI__) || defined(__USE_C99_ALL) || (defined(__STDC_VERSION__) && 199901L <= __STDC_VERSION__) || (defined(__cplusplus) && 201103L <= __cplusplus)
extern _ARMABI int vsnprintf(char * __restrict , size_t ,
const char * __restrict , __va_list ) __attribute__((__nonnull__(3)));
#endif
这是keil mdk里的描述,但是我没包含微库,所以感觉其他编译器也能使用,我没试过。
下面直接给出代码
#include "stdarg.h"
#include "stdio.h"
#define APP_TX_DATA_SIZE 2048
uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];
void uart_printf(UART_HandleTypeDef *huart,const char *format, ...)
{
va_list args;
uint32_t length;
va_start(args, format);
length = vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
va_end(args);
HAL_UART_Transmit(huart,UserTxBufferFS, length,0xffff);
}
测试
方法二
直接找出printf的源码,或者自己写一个printf,我这里在野火的代码里找到的,直接搬过来分享,自己没测试使用,用到的时候再移植吧
static char * itoa ( int value, char * string, int radix );
uint8_t buffer[2] = {0x0d,0x0a};
void USART_printf ( USART_TypeDef * USARTx, char * Data, ... )
{
const char *s;
int d;
char buf[16];
va_list ap;
va_start(ap, Data);
while ( * Data != 0 )
{
if ( * Data == 0x5c )
{
switch ( *++Data )
{
case 'r':
HAL_UART_Transmit(&ESP8266_UartHandle,(uint8_t *)&buffer[0], 1, 0xFFFF);
Data ++;
break;
case 'n':
HAL_UART_Transmit(&ESP8266_UartHandle,(uint8_t *)&buffer[1], 1, 0xFFFF);
Data ++;
break;
default:
Data ++;
break;
}
}
else if ( * Data == '%')
{
switch ( *++Data )
{
case 's':
s = va_arg(ap, const char *);
for ( ; *s; s++)
{
HAL_UART_Transmit(&ESP8266_UartHandle,(uint8_t *)s, 1, 0xFFFF);
while ( __HAL_USART_GET_FLAG (&ESP8266_UartHandle, USART_FLAG_TXE ) == RESET );
}
Data++;
break;
case 'd':
d = va_arg(ap, int);
itoa(d, buf, 10);
for (s = buf; *s; s++)
{
HAL_UART_Transmit(&ESP8266_UartHandle,(uint8_t *)s, 1, 0xFFFF);
while ( __HAL_USART_GET_FLAG (&ESP8266_UartHandle, USART_FLAG_TXE ) == RESET );
}
Data++;
break;
default:
Data++;
break;
}
}
else
{
HAL_UART_Transmit(&ESP8266_UartHandle,(uint8_t *)Data, 1, 0xFFFF);
Data++;
}
while ( __HAL_USART_GET_FLAG (&ESP8266_UartHandle, USART_FLAG_TXE ) == RESET );
}
}
static char * itoa( int value, char *string, int radix )
{
int i, d;
int flag = 0;
char *ptr = string;
if (radix != 10)
{
*ptr = 0;
return string;
}
if (!value)
{
*ptr++ = 0x30;
*ptr = 0;
return string;
}
if (value < 0)
{
*ptr++ = '-';
value *= -1;
}
for (i = 10000; i > 0; i /= 10)
{
d = value / i;
if (d || flag)
{
*ptr++ = (char)(d + 0x30);
value -= (d * i);
flag = 1;
}
}
*ptr = 0;
return string;
}
分享一篇添加链接描述
这篇博客对你有帮助,点个赞呗。
|