【C语言技巧】51单片机支持printf打印

本文档详细介绍了如何使用新唐单片机N76E003AT20初始化串口1,包括配置P16和P02引脚、设置SCON寄存器、波特率设置及中断处理。此外,还提供了串口发送字符和字符串的函数实现,以及支持格式化字符串打印的uart_printf函数,适用于Modbus通信测试。
摘要由CSDN通过智能技术生成

以新唐单片机 N76E003AT20 为例:

首先初始化串口1 :

这里是modbus测试中摘取的一部分,适当删减

注意:要增加以下两个头文件才能使用

  • #include “stdio.h” //sprintf相关函数支持的头文件
  • #include <STDARG.H> //多参数函数支持的头文件。
#include "stdio.h"      //sprintf相关函数支持的头文件。 
#include <STDARG.H>     //多参数函数支持的头文件。

#define UART_PRINTF_EN 	1

/*
********************************************
* 函数名称 : bsp_uart1_init
* 函数说明 : bsp_uart1_init
* 备    注 : 
**********************************************/
void bsp_uart1_init(void)
{
	P16_PushPull_Mode;	//TX引脚
	P02_Quasi_Mode;		//RX引脚
	
	
	SCON_1=0x50;//设置串口1工作在模式1(8位数据,不带奇偶校验)

	clr_TR3;	//停止定时器3 
	
	RH3=0xFF;
	RL3=0x94;	//9600
	
	set_TR3;	//使能定时器3
	set_ES_1;	//使能串口1中断
	
	RS485_UART1_REVC;	
	uart1_busy = 0;	
	
}

/*********************************************
* 函数名称 : uart_char
* 函数说明 : id 0:串口0, 1:串口1, ch:要发送的字符
* 备    注 : 
**********************************************/
void uart_char(u8 id,u8 ch)
{
		switch (id)
		{
			case 0:
//					    RS485_UART0_SEND;//使能485发送			
//							uart0_busy = 1;
//							SBUF=ch;
//							while(uart0_busy);
//							RS485_UART0_REVC;//使能485接收
			
				break;
			case 1:
//							RS485_UART1_SEND;
							uart1_busy = 1;
							SBUF_1=ch;
							while(uart1_busy);	
//							RS485_UART1_REVC;		
				break;
			
			
			default:
				break;
		}
}

/*********************************************
* 函数名称 : uart_string
* 函数说明 : id 0:串口0, 1:串口1, str:要发送的字符串
* 备    注 : 
**********************************************/
void uart_string(u8 id,u8 * str)
{
	while(*str){
		uart_char(id,*str++);
	}	
}

#ifdef	UART_PRINTF_EN

/*********************************************
* 函数名称 : uart_string 串口打印函数。
* 函数说明 : id 0:串口0, 1:串口1, str:要发送的格式化字符串
* 备    注 : 
**********************************************/
void uart_printf(u8 id,const char * str,...)
{
	char xdata buf[32];	//注意数组缓存的大小,打印字符超过数组大小会导致出现死机或者其它问题
	va_list vp;
    va_start(vp, str);
	
    vsprintf(buf,str,vp);
    va_end(vp);
	uart_string(id,buf);
}
#endif

/*********************************************
* 函数名称 : Uart1_ISR
* 函数说明 : 串口1中断处理
* 备    注 : 
**********************************************/
void Uart1_ISR(void) interrupt 15
{
	if(RI_1)
	{
		RI_1=0;
//		uart1_receive_callback();
	}
	
	if(TI_1)
	{
		uart1_busy = 0;
		TI_1=0;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值