89C52单片机之串口

2019-04-15 18:13发布

#include #include #define uint unsigned int #define uchar unsigned char uchar flag = 0; uchar buf = 0x55; //u void init_T1(); //定时器1 void uart_init(); //串口 void UART1_SendData(char dat); //发送数据 void UART1_SendString(char *s); //发送字符串 char putchar(char c); //重写putchar /************主函数******************/ void main() { init_T1(); uart_init(); UART1_SendString("Hello World! "); printf("printf Test! "); printf("Complie Time:%s ", __TIME__); while(1) { if(flag) { ES = 0; SBUF = buf; while(TI ==1) TI = 0; ES = 1; flag = 0; } } } /***********串口中断***************/ void UART_isr(void) interrupt 4 using 0 { TI = 1; buf = SBUF; while(!RI); flag = 1; TI = 0; RI = 0; } /***************定时器1初始化****************/ void init_T1() { TMOD = 0x20; TH1 = 0xfd; TL1 = 0xfd; TR1 = 1; } /****************串口初始化*************/ void uart_init() { SM0 = 0; SM1 = 1; REN = 1; EA = 1; ES = 1; } /*************UART1 发送串口数据**********/ void UART1_SendData(char dat) { ES=0; //关串口中断 SBUF=dat; while(TI!=1); //等待发送成功 TI=0; //清除发送中断标志 ES=1; //开串口中断 } /***********UART1 发送字符串*************/ void UART1_SendString(char *s) { while(*s)//检测字符串结束符 { UART1_SendData(*s++);//发送当前字符 } } /***********重写putchar函数*************/ char putchar(char c) //printf函数会调用putchar() { UART1_SendData(c); return c; }