51单片机利用左移运算制作一组IO流水灯

51单片机利用左移运算制作一组IO流水灯


  • Proteus仿真
    在这里插入图片描述

实例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <REGX52.H>

//毫秒级延时
void delay(unsigned int z)
{
unsigned x,y;
for(x=z; x>>0; x--)
for(y=110; y>>0; y--);
}
void main() {
static int i=0;
while(1) {
P2=~(1<<i);
i++;
delay(800);
if(i==7) {
P2=~(1<<7);//先让i=7执行P2=0x7f(0111 1111)再执行i%=7操作,不然P27只会量一次
delay(800);
i%=7;//当i等于7时,让i等于0
}
}
}

实现左移后右移动流水灯效果

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
#include<reg52.h>
//毫秒级延时
void delay(unsigned int z)
{
unsigned x,y;
for(x=z; x>>0; x--)
for(y=110; y>>0; y--);
}

void main() {

int i = 0;
unsigned count = 0;
unsigned char flag = 0;
P2 = 0x01;

while(1) {
if(flag%2 == 0) {
P2 = ~(0x01 << count);//从P20到P27,依次点亮
} else {
P2 = ~(0x80 >> count);//从P27到P20,依次点亮
}
delay(800);
count++;
if(count >= 8) {
count = 1;
flag++;
}
}
}


  • 仿真效果
    在这里插入图片描述

利用intrins.h头文件中的左移和右移函数实现

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
#include <REGX52.H>
#include <intrins.h>
//毫秒级延时
void delay(unsigned int z)
{
unsigned x,y;
for(x=z; x>>0; x--)
for(y=110; y>>0; y--);
}
void main(){
unsigned char temp,i;

temp = 0XFE;

while(1)
{
for(i = 0; i < 7;i++)
{
P2 = temp;
temp = \_crol\_(temp,1);
delay(800);//500ms延时 11.0592MHZ
}

for(i = 0; i < 7;i++)
{
P2 = temp;
temp = \_cror\_(temp,1);
delay(800);//500ms延时 11.0592MHZ
}
}
}