- /*UART.H*/
- #define uc unsigned char
- #define ui unsigned int
- #define ul unsigned long
- #define iuc idata unsigned char
- #define iui idata unsigned int
- #define iul idata unsigned long
- #define bt bit
- #define swch switch
- #define cs case
- #define whl while
- #define rtn return
- #define brk break
- #define itrpt interrupt
- uart_init(ul baud,ui prty,bt xos)
- {
- if(xos==1)
- {
- P_SW2|=0x80; /*啟動內部擴展區(qū)寄存器訪問功能*/
- XOSCCR|=0xc0; /*啟動外部晶振*/
- while(!(XOSCCR & 1)); /*待晶振頻率穩(wěn)定*/
- CLKDIV=0x00; /*晶振不分頻*/
- CKSEL=0x01; /*選用外部晶振*/
- }
- SCON=0x50; /*設定串口工作方式*/
- PCON=0x7f; /*波特率不倍速*/
- TMOD|=0x20; /*設置T0T1寄存器*/
- AUXR=0xfc; /*配置輔助寄存器*/
- swch(baud)
- {
- cs 4800: TH1=TL1=0x70;
- cs 9600: TH1=TL1=0xb8;
- cs 19200: TH1=TL1=0xdc;
- cs 28800: TH1=TL1=0xe8;
- cs 38400: TH1=TL1=0xee;
- cs 57600: TH1=TL1=0xf4;
- cs 86400: TH1=TL1=0xf8;
- cs 115200: TH1=TL1=0xfa;
- cs 230400: TH1=TL1=0xfd;
- cs 460800: TH1=TL1=0xfe;
- cs 691200: TH1=TL1=0xff;
- }
- TR1=1; /*啟動定時器1*/
- swch(prty)
- {
- cs 0: {
- PS=0;
- IPH=0x00;
- }
- cs 1: {
- PS=1;
- IPH=0x00;
- }
- cs 2: {
- PS=0;
- IPH=0x10;
- }
- cs 3: {
- PS=1; /*將串口1中斷設置為高優(yōu)先*/
- IPH=0x10; /*將串口1中斷設置為最高優(yōu)先*/
- }
- }
- REN=1; /*允許接收串口數(shù)據(jù)*/
- EA=1; /*打開總中斷*/
- ES=1; /*打開串口中斷*/
- P3M1=0x01; /*00000001*/
- P3M0=0x02; /*00000010,將串口接收口設為高阻輸入模式,發(fā)送口設置為強推挽模式*/
- }
- uart_txd(uc udat[])
- {
- ui i;
- ui j=sizeof(udat);
- TI=RI=0;
- for(i=0;i<j;i++)
- {
- SBUF=udat[i];
- while(TI==0)
- {
- ;
- }
- TI=0;
- }
- }
復制代碼
/*下面是主程序*/
- #include <STC8x.H>
- #include <UART.H>
- iui k,j;
- iui txdbuf[13]={'H','E','L','L','O','\x20','W','O','R','L','D','!','\0'};
- main()
- {
- uart_init(9600,3,1);
- while(1)
- {
- uart_txd(txdbuf);
- }
- }
復制代碼 |