单片机程序巧用printf
int sendchar (int ch) { // Write character to Serial Port while (!(U0LSR & 0x20)); return (U0THR = ch); } int getkey (void) { // Read character from Serial Port while (!(U0LSR & 0x01)); return (U0RBR); } 这样,只要在需要用 printf 的文件里#include ;就 可以了,printf 会通过 Retarget 中的 fputc 函数调用 sendchar 来实现串口数据的输出。 事实上,和第一种的方式是一样的。 3、自定义 printf 函数,以 AVR 为例 前面介绍的是在 KEIL 编译器上使用 printf 函数,但 不是所有的编译器平台都能适用,因此有时候我们需要
函数名:fputc 输 入:
输 出: 功能说明: 重定义 getc 函数,这样可以使用 scanff 函数从串口 1 输入数据 ************************************************* *****************************/ int fgetc(FILE *f) { /* 等待串口 1 输入数据 */ while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET) {}
void Uart0_putchar( unsigned char sdbyte) {
UDR0=sdbyte;
while(!(UCSR0A&0x40));
UCSR0A|=0x40; }
///////////////////////////////////////////////// /////// void Uart0_printf(char *str,...) { char buf[128]; unsigned char i = 0; va_list ptr; va_start(ptr,str); vsprintf(buf,str,ptr); while(buf[i]) {
自定义 printf 函数,下面以 AVR 在 GCC 下为例 在 usart.c 中添加如下代码
View Code #include
; #include
;
/************************************************ *********/ //向串口 usart0 发送一个字节函数
/* Loop until the end of transmission */ while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {}
return ch; } /************************************************ *******************************
return (int)USART_ReceiveData(USART1); }
这样,只要在需要用 printf 的文件里#include ;就 可以了,printf 会自已的调用 fputc 函数来实现串口数 据的输出。 2、添加 Retarget.c,实现在 KEIL 下使用 printf 函数, 以 LPC2478 为例
首先在 Keil 安装目录下面 ARM/Startup/Retarget.c 找到 Retarget.c 文件将其复制到你的工程文.c 中添加如下代码
View Code // Implementation of sendchar (also used by printf function to output data)
功能说明: 重定义 putc 函数,这样可以使用 printf 函数从串口 1 打印输出 ************************************************* ******************************/ int fputc(int ch, FILE *f) { /* Place your implementation of fputc here */ /* e.g. write a character to the USART */ USART_SendData(USART1, (uint8_t) ch);
由于不同的编译器 studio 函数不一样,所以使用的 方法也不一样,这需要大家去看编译器的 help 帮助选项, 这里我们以 STM32、51 和 AVR 整理了几个串口打印程序, 供需要的朋友参考。
1、在 KEIL 下使用 printf 函数,以 STM32 为例 在 uart.c 中添加如下代码 View Code /************************************************ ******************************* 函数名:fputc 输 入: 输 出:
Uart0_putchar(buf[i]);
i++; } }
这样有了 printf 格式化输出函数,随时能把需要的 变量打印到 pc 机或液晶上,调试起来就方便多了。
单片机程序巧用 printf
当我们在调试代码时,通常需要将程序中的某个变 量打印至 PC 机上,来判断我们的程序是否按预期的运行, printf 函数很好的做到了这一点,它能直接以字符的方 式输出变量名和变量的值。 printf 函数在使用时,不仅仅要初始化串口,还需要其 它的一些设置或者要调用其它的一些函数 否则 printf 函数将不能按我们想要的方式执行。