51單片機(jī)串口接收數(shù)據(jù)
單片機(jī)每次發(fā)送或者接受完數(shù)據(jù)(8位數(shù)據(jù)將保存在緩沖區(qū)中),會自動觸發(fā)接受或者發(fā)送中斷。因此只需要中斷置位以后再緩沖區(qū)中讀數(shù)據(jù)(或者發(fā)送數(shù)據(jù))。
1 /*************************************************
2 *receive code(HEX)
3 * $ P M T K 1 8 0 * 3 B n r
4 * 24 50 4D 54 4B 31 38 30 2A 33 42 0D 0A
5 *************************************************/
6
7 unsigned char code CmdData[dataMax] = {0x24,0x50,0x4D,0x54,0x4B,0x31,
8 0x38,0x30,0x2A,0x33,0x42,0x0D,0x0A};
9
10
11 /*************************************************
12 * UART interrupt subroutine
13 *********************************/
14 void UART_ISR (void) interrupt 4 //interrupt address is 0x0023
15 {
16
17 if (RI) //check Tx or Rx interrupt
18 {
19 RI = 0; //clear RI by software for next reception
20
21 if((TmpData = SBUF) == CmdData[index])
22 {
23 index++;
24 if(index == 13)
25 {
26 index = 0;
27 recv_flag = 1;
28 EA = 0; //disable global interrupt
29 }
30
31 }
32 else
33 {
34 index = 0;
35 }
36 }
37 }
38 /*************************************************
39 * Initial Timer 1
40 **************************************************/
41 void Timer1_Init (void)
42 {
43 TMOD = 0x20; //configure Timer 1 as auto-reload 8-bit mode
44 PCON |= 0x80; //double baud rate enable
45 TL1 = TH1 = U8BAUD_TIMER1; //baud rate 9600bps@22.1184MHz
46 TR1 = 1; //Timer 1 run
47 }
48
49 /*************************************************
50 * Main function
51 **************************************************/
52 void main (void)
53 {
54
55 P0OR |= 0x01; //enable P0 internal pull-up
56
57 #if BAUD_SOURCE
58 Timer2_Init();
59 #else
60 Timer1_Init();
61 #endif
62
63 SCON = 0x52; /*initial UART as mode 1, receive enable,
64 TI should be set before using "printf"*/
65 ES = 1; //enable UART interrupt
66 EA = 1; //enable global interrupt
67 delay_ms(700); // >= 700ms
68 while(1)
69 {
70 while(recv_flag)
71 {
72 recv_flag = 0;
73 P00 = 0; //with reset contrl
74 delay_ms(300); // >= 300mS 28/November/2014
75 P00 = 1;
76 delay_ms(100);
77 EA = 1;
78 }
79 //stop_key();
80 while(!P10);
81 }
82 }