一、串口1接线图
1、下面是单片机外接电路图,P30,P31分别用于RXD和TXD功能引脚
2、我们来查看单片机手册
串口1需要设置的寄存器
串口1的功能脚配置选择位,看电路图选择的是P3.0,P3.1。
3、串口1:SCON控制寄存器
设置为0x50:0101 0000。(SCON=0x50)
4、数据寄存器
5、电源管理寄存器
6、辅助寄存器1使用
AUXR |= 0x01;//串口1选择定时器2为波特率发生器
AUXR |= 0x04;//定时器2时钟为Fosc,即1T
AUXR |= 0x10;//启动定时器2
7、串口波特率的计算公式
定时器2重载值:65536-35000000/(4 * 115200) = 0xFFB4。
7、定时器2的设置
特别注意在使用串口时,这个需要设置为35.0MHZ。否则串口调试助手不能正常显示。
二、串口1代码
#include "uart.h"
#include "delay.h"
void Uart_Init()
{SCON = 0x50;//模式1 8位数据 可变波特率AUXR |= 0x01;AUXR |= 0x04;T2H = 0xFF;T2L = 0xB4;AUXR |= 0x10;ES = 1;//打开串口中断EA = 1;
}void Uart_SendByte(unsigned char byte)
{SBUF = byte;
}void Uart_SendDat(unsigned char *dat)
{while(*dat != '\0'){Uart_SendByte(*dat);dat++;Delay_ms(50);}
}
#include "delay.h"//延时1us
void Delay1us()
{unsigned char i;_nop_();_nop_();i = 9;while(--i);
}//延时10us
void Delay10us()
{unsigned char i;_nop_();_nop_();i = 114;while(--i);
}//延时1ms
void Delay1ms()
{unsigned char i,j;_nop_();_nop_();i = 46;j = 113;do{while(--j);}while(--i);
}void Delay_ms(unsigned int ms)
{unsigned int i = 0;for(i = 0;i < ms;i++){Delay1ms();}
}
#include "stc8g.h"
#include "uart.h"
#include "delay.h"sbit LED_R = P0^5;
sbit LED_Y = P0^6;
sbit LED_G = P0^7;unsigned char uartRec;void IO_Init()
{P_SW1= 0x00;//S1_S P3.0 P3.1P0M0 = 0x00;P0M1 = 0x00;P1M0 = 0x00;P1M1 = 0x00;P2M0 = 0x00;P2M1 = 0x00;P3M0 = 0x00;P3M1 = 0x00;P4M0 = 0x00;P4M1 = 0x00;P5M0 = 0x00;P5M1 = 0x00;
}void main()
{IO_Init();Uart_Init();//串口初始化while(1){Uart_SendDat("sdhak");}
}void Uart_Isr() interrupt 4
{if(TI == 1){TI = 0;LED_R = !LED_R;}if(RI == 1){uartRec = SBUF;RI = 0;LED_Y = !LED_Y;SBUF = uartRec;}
}