6.串口发送以及接收例程
#include "reg51.h" #include "intrins.h" typedef unsigned char BYTE; typedef unsigned int WORD; BYTE code_tab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff}; char arry[10]="I CAN PLAY"; unsigned char x; #define FOSC 11059200//12000000L //系统频率 #define BAUD 115200 //串口波特率 #define NONE_PARITY 0 //无校验 #define ODD_PARITY 1 //奇校验 #define EVEN_PARITY 2 //偶校验 #define MARK_PARITY 3 //标记校验 #define SPACE_PARITY 4 //空白校验 #define PARITYBIT NONE_PARITY //定义校验位 sfr AUXR = 0x8e; //辅助寄存器 sfr P_SW1 = 0xA2; //外设功能切换寄存器1 #define S1_S0 0x40 //P_SW1.6 #define S1_S1 0x80 //P_SW1.7 sbit P22 = P2^2; bit busy; void SendData(BYTE dat); void SendString(char *s); void main() { ACC = P_SW1; ACC &= ~(S1_S0 | S1_S1); //S1_S0=0 S1_S1=0 P_SW1 = ACC; //(P3.0/RxD, P3.1/TxD) // ACC = P_SW1; // ACC &= ~(S1_S0 | S1_S1); //S1_S0=1 S1_S1=0 // ACC |= S1_S0; //(P3.6/RxD_2, P3.7/TxD_2) // P_SW1 = ACC; // // ACC = P_SW1; // ACC &= ~(S1_S0 | S1_S1); //S1_S0=0 S1_S1=1 // ACC |= S1_S1; //(P1.6/RxD_3, P1.7/TxD_3) // P_SW1 = ACC; //#if (PARITYBIT == NONE_PARITY) SCON = 0x50; //8位可变波特率 //#elif (PARITYBIT == ODD_PARITY) || (PARITYBIT == EVEN_PARITY) || (PARITYBIT == MARK_PARITY) // SCON = 0xda; //9位可变波特率,校验位初始为1 //#elif (PARITYBIT == SPACE_PARITY) // SCON = 0xd2; //9位可变波特率,校验位初始为0 //#endif AUXR = 0x40; //定时器1为1T模式 TMOD = 0x20; //定时器1为模式2(8位自动重载) TL1 = (256 - (FOSC/32/BAUD)); //设置波特率重装值 TH1 = (256 - (FOSC/32/BAUD)); TR1 = 1; //定时器1开始工作 ES = 1; //使能串口中断 EA = 1; while(1) { // SendString(arry); SendString("I CAN PLAY~~\r\n");//上位机显示接收文本模式 // SendData(x); } } void Uart() interrupt 4 using 1 { if (RI)//单片机接收数据,发送数字0~9,可在数码管上显示,发送hex模式 { RI = 0; //清除RI位 // P0 = SBUF; x=SBUF;//将缓存器的数据赋值给x P0=0xff; //消隐 P2|=0xe0; P2&=0x1f; P0=code_tab[x]; //段选 P2|=0xe0; P2&=0x1f; P0=0x01; //位选第一位 P2|=0xc0; P2&=0x3f; } if (TI) { TI = 0; //清除TI位 busy = 0; //清忙标志 } } void SendData(BYTE dat) { while (busy); //等待前面的数据发送完成 ACC = dat; //获取校验位P (PSW.0) if (P) //根据P来设置校验位 { #if (PARITYBIT == ODD_PARITY) TB8 = 0; //设置校验位为0 #elif (PARITYBIT == EVEN_PARITY) TB8 = 1; //设置校验位为1 #endif } else { #if (PARITYBIT == ODD_PARITY) TB8 = 1; //设置校验位为1 #elif (PARITYBIT == EVEN_PARITY) TB8 = 0; //设置校验位为0 #endif } busy = 1; SBUF = ACC; //写数据到UART数据寄存器 } void SendString(char *s) { while (*s) //检测字符串结束标志 { SendData(*s++); //发送当前字符 } } 记不住可以看手册!! #include "reg51.h" #include "intrins.h" typedef unsigned char BYTE; typedef unsigned int WORD; #define FOSC 11059200L #define BAUD 115200 sfr AUXR=0x8e; //辅助寄存器 sbit P22=P2^2; bit busy; void SendData(BYTE dat); void SendString(char *s); void main() { SCON=0x50; AUXR=0x40; //设置定时器T1为1T,即一个机器周期模式 TMOD=0x20; TL1=(256-(FOSC/32/BAUD)); TH1=(256-(FOSC/32/BAUD)); TR1=1; ES=1; EA=1; SendString("Hello"); while(1); } void Uart() interrupt 4 using 1 { if(RI) { RI=0; P0=SBUF; } if(TI) { TI=0; busy=0; } } void SendData(BYTE dat) { while(busy); busy=1; SBUF=dat; } void SendString(char *s) { while(*s) { SendData(*s++); } }
|