STC 51 单片机 串口通信实验

来源:互联网 发布:mac版千牛怎么更新 编辑:程序博客网 时间:2024/05/01 01:53

        以后不再好高骛远,要脚踏实地地做好每件事,要踏踏实实地学好单片机。

        作为第一个博客,首先谈谈我写的一个51单片机串口通信程序。

        我用的是一款增强版51单片机,型号为STC12LE5A60S2。

        1、查询方式,下面是我的源代码:

/*======================================单片机型号:STC12LE5A60S2串口1,波特率发生器使用定时器1,定时器1工作于8位自动重载模式Author:fightingDate:2013-07-21=======================================*/#include <reg51.h>sfr AUXR = 0x8e;void uart_init(void){    TMOD &= 0x0f;    TMOD |= 0x20;//8-bit,auto-reload    PCON &=0x7f;    //Don't double baund rate    SCON = 0x50;    //8-bit data, changeable baund rate    AUXR |= 0x40;   //Choose 1T mode    AUXR &= 0xfe;   //UART 1 chooses timer 1 as baund rate generator    TL1 = 0x98;     //in order to operate on 9600 when the clock is 32MHz    TH1 = 0x98;    ET1 = 0;    TR1 = 1;}void main(void){    unsigned char response;    uart_init();    while(1)    {if(RI == 1){RI = 0;response = SBUF;SBUF = response;}    }}

        2、中断方式

/*======================================单片机型号:STC12LE5A60S2串口1,波特率发生器使用定时器1,定时器1工作于8位自动重载模式中断方式Author:fightingDate:2013-07-21=======================================*/#include <reg51.h>sfr AUXR = 0x8e;unsigned char response;void uart_init(void){    TMOD &= 0x0f;    TMOD |= 0x20;//8-bit,auto-reload    PCON &=0x7f;    //Don't double baund rate    SCON = 0x50;    //8-bit data, changeable baund rate    AUXR |= 0x40;   //Choose 1T mode    AUXR &= 0xfe;   //UART 1 chooses timer 1 as baund rate generator    TL1 = 0x98;     //in order to operate on 9600 when the clock is 32MHz    TH1 = 0x98;    ET1 = 0;        //Disable timer 1 interrupt    TR1 = 1;        //Turn on timer 1    ES = 1;         //Enable serial interrupt    EA = 1;         //Enable global interrupt}void serial() interrupt 4 using 3{    if(RI == 1)    {        RI = 0;        response = SBUF;TI = 0;SBUF = response;while(TI == 0);    }}void main(void){    uart_init();    while(1);}