- include <STC15F2K60S2.H>
- typedef unsigned char uchar;
- #define SYS_CLOCK 22118400L
- #define BAUDRATE1 9600
- #define BAUDRATE2 9600
- void init_uart1()
- {
- PCON &= 0x7F; //波特率不倍速
- SCON = 0x50; //8位数据,可变波特率
- AUXR |= 0x40; //定时器1时钟为Fosc,即1T
- AUXR &= 0xFE; //串口1选择定时器1为波特率发生器
- TMOD &= 0x0F; //清除定时器1模式位
- TMOD |= 0x20; //设定定时器1为8位自动重装方式
- TL1 = 256 - SYS_CLOCK/32/BAUDRATE1; //设定定时初值
- TH1 = 256 - SYS_CLOCK/32/BAUDRATE1; //设定定时器重装值
- ET1 = 0; //禁止定时器1中断
- TR1 = 1; //启动定时器1
- }
- void init_uart2()
- {
- S2CON = 0x50; //8位数据,可变波特率
- AUXR |= 0x04; //定时器2时钟为Fosc,即1T
- T2L = (65536 - SYS_CLOCK/BAUDRATE2/4); //设定定时初值
- T2H = (65536 - SYS_CLOCK/BAUDRATE2/4) >> 8; //设定定时初值
- AUXR |= 0x10; //启动定时器2
- }
- void test_send_byte(uchar dat)
- {
- IE2 &= 0xfe; //disable uart2 interrupt
- P_SW2 |= 0x01; //change uart2 port to P4.6/P4.7
- S2BUF = dat;
- while(!(S2CON & 0x02));
- S2CON &= 0xfd;
- // P_SW2 &= 0xfe; //change uart2 port to P1.0/P1.1
- IE2 |= 0x01; //enable uart2 interrupt
- }
- uchar g_buf = 0;
- uchar g_received = 0;
- void main()
- {
- init_uart1();
- init_uart2();
- EA = 1;
- ES = 1;
- IE2 = 0x01;
- test_send_byte(0x55);
- while(1)
- {
- // while(!g_received);
- // g_received = 0;
- // test_send_byte(g_buf);
- }
- }
- void uart1() interrupt 4
- {
- if(RI)
- {
- P23 = 0;
- RI = 0;
- test_send_byte(SBUF);
- }
- }
以上程序串口1接收来自PC端串口调试助手的数据,并及时通过串口2返回给PC端的另一个串口调试助手窗口。现在的问题是,若test_send_byte()函数中P_SW2 &= 0xfe;语句不注释掉的话,把程序下载进单片机,然后串口2发送0x55,即52行的代码test_send_byte(0x55);;给串口1发数据,串口1中断正常,串口2也能把串口1接收到的数据发送给PC。单是我给单片机断电后再上电,第52行的代码似乎执行了两次,即PC端收到了两个0x55,然后给串口1发送数据,串口1无法进入中断(若进入中断,P23引脚应该为低电平,实际测得为高),串口2也就没有给PC返回数据了。但是当我将test_send_byte()函数中P_SW2 &= 0xfe;语句注释掉以后,一切又恢复正常了,即串口1可以中断,接收数据;串口2也能相应地发送数据给PC,0x55也只收到一次。第一次发帖求助,语言组织可能不好,望各路大神指教。
|