关于printf重定向到串口

来源:互联网 发布:华为acl mac过滤 编辑:程序博客网 时间:2024/04/27 19:58
我在某个CortextM3的源码里的debug.c找到了fputc。应该说,某些系统是通过fputc建立联系,而不是putchar的。如下:
<span style="font-family:Verdana;font-size:14px;">void fputc_hook(char ch){    if (DebugType == 0)    {        UARTWriteByte(ch, 1000);    }    else    {        VirtualUartWrite(ch);    }}int fputc(int ch, FILE *f){    uint8 dgbBuffer[DEBUG_TIME_LEN];    uint32 tmpcnt, i;    if (ch == '\n')    {                tmpcnt = SysTickCounter;        for (i = 0; i < DEBUG_TIME_LEN; i++)        {            dgbBuffer[i] = tmpcnt % 10;            tmpcnt = tmpcnt / 10;        }                fputc_hook('\r');        fputc_hook('\n');        fputc_hook('[');        for (i = 0; i < DEBUG_TIME_LEN; i++)        {            fputc_hook(dgbBuffer[DEBUG_TIME_LEN - 1 -i]+0x30);            if (DEBUG_TIME_LEN - 1 -i == 2)            {                fputc_hook('.');            }        }        fputc_hook(']');                return OK;    }        fputc_hook(ch);    return OK;}</span>

下面是参考文章的转载:

http://blog.chinaunix.net/uid-27631233-id-3345008.html

    在实际工作中,遇到了这么一个问题,需要向不同的串口传输ASCII码,无疑使用printf函数是最方便的。然而printf打印出的信息无法选择出口。在网上搜到的程序,printf要调用fputc函数发送字符。该函数如下:


int fputc(int ch, FILE *f)

{

  /* e.g. write a character to the USART */

  USART_SendData(USART1, (uint8_t) ch);


  /* Loop until the end of transmission */

  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)

  {}


  return ch;

}


    入口参数有字符和字符要输出到的文件指针。根据搜索,printf函数输出到stdout,而fprintf可以指定字符到达的文件。可FILE结构体中,没有一个是与串口相关的。


typedef struct {

  char *fpos; /* Current position of file pointer (absolute address) */

  void *base; /* Pointer to the base of the file */

  unsigned short handle; /* File handle */

  short flags; /* Flags (see FileFlags) */

  short unget; /* 1-byte buffer for ungetc (b15=1 if non-empty) */

  unsigned long alloc; /* Number of currently allocated bytes for the file */

  unsigned short buffincrement; /* Number of bytes allocated at once */

} FILE;


    该如何重定向呢?不知道。但有一个弥补的方法。

    自己定义n个FILE*指针,并任意赋值。在fputc中利用if..else来做判断,代码如下:


FILE* FileUart1 = (FILE*)0x19;

FILE* FileUart2 = (FILE*)0x28;

int fputc(int ch, FILE *f) {

  if ( f == FileUart1 ) {

    USART_SendData(COM_USART[0], (uint8_t) ch);

    while (USART_GetFlagStatus(COM_USART[0], USART_FLAG_TC) == RESET){}

  }

  else if ( f == FileUart2 ) {

    USART_SendData(COM_USART[1], (uint8_t) ch);

    while (USART_GetFlagStatus(COM_USART[1], USART_FLAG_TC) == RESET){}

  }

}


    这样,fprintf(FileUart1,...)和fprintf(FileUart2,...)便能向不同的串口发送数据。哈哈,虽然没有真正做到重定向,只是用了个歪招,但最初的目的还是达到了。

    如果哪位牛人能告知如何真正重定向,感激感激~~~~


    还要请问,如何使用__DEBUG__宏定义才能使fprintf("val is %d", val)或fprintf("val1 is %d, val2 is %d", val1, val2)在程序中任意被编译上或编译掉。当然,不包括#ifdef..#endif方法。不这么做就是为了代码清晰一些,便于阅读。谢谢啊~~
0 0
原创粉丝点击