题目
由上位机发送1给单片机时,蜂鸣器以400ms频率发声,发2时以200ms频率发声,发3时以100ms频率发声,发4时关闲蜂鸣器。
分析,
这道题这题难度不大,但是还有值得总结的地方,首先是执行串口通信的时候,需要将串口通信的中断关闭,因为此题涉及到定时器0 的中断因此,在4输入时候,关闭定时器0 的中断来解决问题, 来彻底解决此程序的中断,这点容易忘记,其他的之前都总结过了,就没了,还有,当输入4时后之后就没办法使用了,因为定时器0 就无法打开,因此这点不是很方便,但是不知道怎么解决,我看别的别人的代码也没有解决此问题,也就搁置了
代码
1 # include <reg52.h>
2 # define uint unsigned int
3 # define uchar unsigned char
4 uchar flag,a,i,b;
5 sbit beep = P2^ 3;
6 void inti();
7 void main()
8 {
9 inti();
10 beep = 1;
11 while( 1)
12 {
13 if(flag == 1)
14 {
15 ES = 0;
16 if(a == 0x01||a == 0x02||a == 0x03)
17 {
18 if(a == 0x01)
19 b = 20;
20 if(a == 0x02)
21 b = 10;
22 if(a == 0x03)
23 b = 5;
24 }
25
26 if(a == 0x04)
27 {
28 TR0 = 0;
29 beep = 1;
30 }
31 ES = 1;
32 // TR0 = 1;
33 flag = 0;
34 }
35 }
36 }
37 void inti()
38 {
39 TMOD = 0x21;
40 TH0 = ( 65536- 50000)/ 256;
41 TL0 = ( 65536- 50000)% 256;
42 TH1 = 0xfd;
43 TL1 = 0xfd;
44 TR1 = 1;
45 REN = 1;
46 SM0 = 0;
47 SM1 = 1;
48 EA = 1;
49 ES = 1;
50 ET0= 1;
51 TR0 = 1;
52 }
53 void se () interrupt 4
54 {
55 RI = 0;
56 flag = 1;
57 a = SBUF;
58 }
59 void time1 () interrupt 1
60 {
61 TH0 = ( 65536- 50000)/ 256;
62 TL0 = ( 65536- 50000)% 256;
63 i++;
64 if(i == b)
65 {
66 i = 0;
67 beep = ~beep;
68 }
69
2 # define uint unsigned int
3 # define uchar unsigned char
4 uchar flag,a,i,b;
5 sbit beep = P2^ 3;
6 void inti();
7 void main()
8 {
9 inti();
10 beep = 1;
11 while( 1)
12 {
13 if(flag == 1)
14 {
15 ES = 0;
16 if(a == 0x01||a == 0x02||a == 0x03)
17 {
18 if(a == 0x01)
19 b = 20;
20 if(a == 0x02)
21 b = 10;
22 if(a == 0x03)
23 b = 5;
24 }
25
26 if(a == 0x04)
27 {
28 TR0 = 0;
29 beep = 1;
30 }
31 ES = 1;
32 // TR0 = 1;
33 flag = 0;
34 }
35 }
36 }
37 void inti()
38 {
39 TMOD = 0x21;
40 TH0 = ( 65536- 50000)/ 256;
41 TL0 = ( 65536- 50000)% 256;
42 TH1 = 0xfd;
43 TL1 = 0xfd;
44 TR1 = 1;
45 REN = 1;
46 SM0 = 0;
47 SM1 = 1;
48 EA = 1;
49 ES = 1;
50 ET0= 1;
51 TR0 = 1;
52 }
53 void se () interrupt 4
54 {
55 RI = 0;
56 flag = 1;
57 a = SBUF;
58 }
59 void time1 () interrupt 1
60 {
61 TH0 = ( 65536- 50000)/ 256;
62 TL0 = ( 65536- 50000)% 256;
63 i++;
64 if(i == b)
65 {
66 i = 0;
67 beep = ~beep;
68 }
69
70 }