STC8H8K64U开发板实现的串口重定向输出,附源代码

STC8H8K64U开发板实现的串口重定向输出,附源代码

/***
 * 实现功能:STC8H8K64U芯片的printf重映射
 * 主    频:11.0592MHz
***/
#include "stdio.h"		//标准输入输出库
#include "stc8h.h"		//stc8h库

typedef     unsigned char   u8;
typedef     unsigned int    u16;
typedef     unsigned long   u32;

#define MAIN_FOSC 11059200UL
#define BRT (65536 - (MAIN_FOSC / 115200+2) / 4)


/***
 * 函数功能:串口初始化
***/
void UartInit()
{
    // 设置SCON寄存器
    SCON = 0x50; // 模式1,8位数据,可变波特率

    // 设置波特率生成器
    T2L = BRT;
    T2H = BRT >> 8;

    // 设置AUXR寄存器
		AUXR |= 0x15;
		
	// 设置 P_SW1.6 = 1,即使用 P3.6 和 P3.7
	P_SW1 |= 0x40;   
}


/***
 * 函数功能:延时函数
***/
void delay_ms(u16 ms)
{
     u16 i;
     do{
          i = MAIN_FOSC / 10000;
          while(--i);   //10T per loop
     }while(--ms);
}


/***
 * 函数功能:发送一个字符
***/
void UartPutc(unsigned char dat)
{
    SBUF = dat;				//数据写入缓冲区
    while(TI==0);			//等待传输完成
    TI = 0;						//清除传输中断标志
}

/***
 * 函数功能:发送字符数组
***/
void UartSendStr(char *p)
{
	while (*p)
	{
		UartPutc(*p++);
	}
}



/***
 * 函数功能:printf函数重定向函数
***/
char putchar(char c)
{
    UartPutc(c);
    return c;
}


void main()
{
	P_SW2 |= 0x80; //使能访问 XFR
	
	//设置为准双向口
//	P0M0 = 0x00;
//	P0M1 = 0x00;
//	P1M0 = 0x00;
//	P1M1 = 0x00;
	P2M0 = 0x00;			
	P2M1 = 0x00;			//led灯
	P3M0 = 0x00;
	P3M1 = 0x00;
//	P4M0 = 0x00;
//	P4M1 = 0x00;
//	P5M0 = 0x00;
//	P5M1 = 0x00;
	
	UartInit();
	ES = 1;			// 使能串口1中断
	EA = 1;			// 使能总中断
	

	while (1)
	{
		P21 = 0;		//LED On
    	delay_ms(500);
    	P21 = 1;		//LED Off
		delay_ms(500);	
		
		UartSendStr("this is a test!\r\n");
		printf("This is a printf_test!\r\n");
	}
}

程序运行输出结果:
STC8H8K64U开发板实现的串口重定向输出,附源代码_第1张图片

你可能感兴趣的:(单片机,嵌入式硬件)