51单片机学习之流水灯蜂鸣器

流水灯

在代码中的延时均使用软件延时,即函数嵌套循环体进行延时;

位输出实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<reg52.h>
#define uint unsigned int

#define on 1
#define off 0

sbit led_0 = P1 ^ 0;
sbit led_1 = P1 ^ 1;
sbit led_2 = P1 ^ 2;
sbit led_3 = P1 ^ 3;
sbit led_4 = P1 ^ 4;
sbit led_5 = P1 ^ 5;
sbit led_6 = P1 ^ 6;
sbit led_7 = P1 ^ 7;

//延时函数
void Delay(uint ms){
uint i ,j;
for(i = ms; i > 0; i--){
for(j = 112; j>0; j--);
}
}

void main(){
while(1){
led_0 = on;
Delay(200);
led_0 = off;

led_1 = on;
Delay(200);
led_1 = off;

led_2 = on;
Delay(200);
led_2 = off;

led_3 = on;
Delay(200);
led_3 = off;

led_4 = on;
Delay(200);
led_4 = off;

led_5 = on;
Delay(200);
led_5 = off;

led_6 = on;
Delay(200);
led_6 = off;

led_7 = on;
Delay(200);
led_7 = off;
}
}

循环位移实现

1
2
3
4
5
P1 = 0xfe	//1111 1110
while(1){
Delay(1000);
P1 = _crol_(P1,1); //将P1左移一位
}

_crol_()函数的使用,必须要加上#include "intrins.h" ,引入头文件,该函数的原型为:

1
unsigned char _crol_(unsigned char val,unsigned char n);

函数功能:以位形式将 val 左移 n 位,该函数与8051“RLA”指令相关。如果二进制数为 01010101 那么 _crol_(1) 左移1位后将高位补低位,结果10101010。

移位操作实现

1
2
3
4
5
6
7
8
9
int i = 0;
while(1){
P1 = 0xfe;
for (i = 0; i < 8; i++){
Delay(1000);
P1 <<= 1;
P1 = P1 | 0X01;
}
}

通过每次位移一位,再与0x01进行或操作,这样每次都有一位是低电位,从而实现流水灯。

蜂鸣器