MAPLAB X IDE中加入printf函数的三种办法目录标题
开发环境
printf在程序的开发调试中跟查看示波器一样的重要,并可以就是显示调试信息。
单片机:PIC24FJ256
IDE: MPLAB X IDE v6.15
方法1 :重写fputc函数。
通过<stdio.h>文件中,重写fputc函数。
局限:该方法目前只适用于串口1。要改到串口2/3/4测试过无效。
#include <stdio.h>
//printf函数映射
/*****************************
函数名:void fputc( char ch )
功能:重定向printf函数
#fputc函数实现,printf需要*/
int fputc(int ch, FILE* f)
{
TX1_IF = 0; //清发送中断标志
U1TXREG = ch; //送发送寄存器
while (!U1STAbits.TRMT);
return ch;
}
方法2:宏定义方式
该方式最为简洁。可用于串口1,串口2。对串口3,4 无效。
只需要在.c 文件头上加上以下定义即可。
extern int __C30_UART;
//通过这个变量就可以灵活的将printf、scanf等标准函数的输入输出定义到需要的串口上。
//使用串口1:__C30_UART = 1;
//使用串口2:__C30_UART = 2;
__C30_UART = 2;
方法3:利用mcc自动生成方式的冲定向
自动生成的核心代码有主要是以下两个函数。
void UART3_Write(uint8_t txData)
{
while(U3STAbits.UTXBF == 1)
{
}
U3TXREG = txData; // Write the data byte to the USART.
}
int __attribute__((__section__(".libc.write"))) write(int handle, void *buffer, unsigned int len)
{
unsigned int i;
for (i = len; i; --i)
{
UART3_Write(*(char*)buffer++);
}
return(len);
}