C51实现流水灯
kying-star的博客
# C51实现流水灯
# 1、进行左移和右移逻辑运算
#include <reg52.h>
void delay300ms(void) //误差 0us
{
unsigned char a, b, c;
for (c = 123; c > 0; c--)
for (b = 116; b > 0; b--)
for (a = 9; a > 0; a--)
;
}
void main()
{
unsigned char cnt = 0; //定义计数变量 cnt,用于移位控制
while (1)
{
for (cnt = 0; cnt < 8; cnt++)
{
P2 = ~(0x01 << cnt);
delay300ms();
}
for (cnt = 7; cnt >= 0; cnt--)
{
P2 = ~(0x01 << cnt);
delay300ms();
}
}
}
# 2、将灯的状态编写成字符型数组
#include <reg52.h>
void delay500ms(void) //误差 0us
{
unsigned char a, b, c;
for (c = 23; c > 0; c--)
for (b = 152; b > 0; b--)
for (a = 70; a > 0; a--)
;
}
void main()
{
unsigned int i = 0;
unsigned char cnt = 0;
unsigned char leds[8] = {0xFE, 0xFD, 0xFB, 0xF7, 0xEF, 0xDF, 0xBF, 0x7F};
while (1)
{
for (i = 0; i < 8; i++)
{
delay500ms();
P2 = leds[i];
delay500ms();
}
for (i = 7; i > 0; i--)
{
delay500ms();
P2 = leds[i];
delay500ms();
}
}
}
# 3、调用(循环左移和右移)库函数
#include <reg52.h>
#include <intrins.h>
void delay500ms(void) //误差 0us
{
unsigned char a, b, c;
for (c = 23; c > 0; c--)
for (b = 152; b > 0; b--)
for (a = 70; a > 0; a--)
;
}
void main()
{
unsigned int i = 0; //定义循环变量 i,用于软件延时
unsigned char a = 0xFE;
while (1)
{
for (i = 0; i < 8; i++)
{
delay500ms();
P2 = a;
a = _crol_(a, 1);
delay500ms();
}
for (i = 0; i < 8; i++)
{
delay500ms();
P2 = a;
a = _cror_(a, 1);
delay500ms();
}
}
}