本帖最后由 xiaolong_ba 于 2016-7-1 12:22 编辑
写在最前面
欢迎加入Cypress BLE技术讨论群130946269进行技术讨论,供应商和销售就不要进来了,发现了一律都T掉(不喜欢群里一堆广告,而不是持术问题)
一、前言
最近在使用PSOC BLE,为了调试方便把信息通过串口打印出来。所以想要用printf函数重定向至串口,由于PSOC Creator默认用的是GCC编译器,所以我们只需要重写_write()函数即可,因为GCC编译环境下printf函数最终调用的是_write()函数。但是为了兼容其他编译器,常规的写法如下所示:- #if defined(__ARMCC_VERSION)
- /* For MDK/RVDS compiler revise fputc function for printf functionality */
- struct __FILE
- {
- int handle;
- };
- enum
- {
- STDIN_HANDLE,
- STDOUT_HANDLE,
- STDERR_HANDLE
- };
- FILE __stdin = {STDIN_HANDLE};
- FILE __stdout = {STDOUT_HANDLE};
- FILE __stderr = {STDERR_HANDLE};
- int fputc(int ch, FILE *file)
- {
- int ret = EOF;
- switch( file->handle )
- {
- case STDOUT_HANDLE:
- UART_DEB_UartPutChar(ch);
- ret = ch ;
- break ;
- case STDERR_HANDLE:
- ret = ch ;
- break ;
- default:
- file = file;
- break ;
- }
- return ret ;
- }
- #elif defined (__ICCARM__) /* IAR */
- /* For IAR compiler revise __write() function for printf functionality */
- size_t __write(int handle, const unsigned char * buffer, size_t size)
- {
- size_t nChars = 0;
- if (buffer == 0)
- {
- /*
- * This means that we should flush internal buffers. Since we
- * don't we just return. (Remember, "handle" == -1 means that all
- * handles should be flushed.)
- */
- return (0);
- }
- for (/* Empty */; size != 0; --size)
- {
- UART_DEB_UartPutChar(*buffer++);
- ++nChars;
- }
- return (nChars);
- }
- #else /* (__GNUC__) GCC */
- /* For GCC compiler revise _write() function for printf functionality */
- int _write(int file, char *ptr, int len)
- {
- int i;
- file = file;
- for (i = 0; i < len; i++)
- {
- UART_DEB_UartPutChar(*ptr++);//这里替代成UART的发送单字节的函数即可
- }
- return len;
- }
- #endif /* (__ARMCC_VERSION) */
重写了_write()函数,最后编译即可使用printf()函数通过串口打印出串口信息了。切记,必须还要把Heap Size(Bytes)设大点的值,不然printf函数没法打印串口消息,但是必须要小于芯片的RAM大小。修改Heap Size(Bytes)如下图所示:
至此,现在就可以用Printf函数打印串口消息 |