如题,使用c语言编写程序实现流水灯和流水灯左右循环
流水灯实现有四种方法,下面一一展示。
// 方法1
#include <reg52.h>
#define led P2
typedef unsigned int u16;
void delay(u16 i)
{
while(i--);
}
void main()
{
while(1)
{
led = 0Xfe;
delay(50000);
led = 0xfd;
delay(50000);
led = 0xfb;
delay(50000);
led = 0xf7;
delay(50000);
led = 0xef;
delay(50000);
led = 0xdf;
delay(50000);
led = 0xbf;
delay(50000);
led = 0x7f;
delay(50000);
}
}
// 方法2
#include <reg52.h>
#define led P2
typedef unsigned int u16;
typedef unsigned char u8;
void delay(u16 i)
{
while(i--);
}
u8 code table[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f};
void main()
{
while(1)
{
u8 i;
for(i=0; i<8; i++)
{
led = table[i];
delay(50000);
}
}
}
// 方法3
#include "reg52.h"
sbit LED1=P2^0;
#define LED_PORT P2
typedef unsigned int u16;
typedef unsigned char u8;
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
u8 i=0;
while(1)
{
for(i=0;i<8;i++)
{
LED_PORT=~(0x01<<i); //将 1 右移 i 位,然后取反将结果赋值到 LED_PORT
delay_10us(50000);
}
}
}
// 方法4
#include "reg52.h"
#include "intrins.h"
#define LED_PORT P2 //使用宏定义P2端口
typedef unsigned int u16;
typedef unsigned char u8;
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
u8 i=0;
LED_PORT=~0x01;
delay_10us(50000);
while(1)
{
for(i=0;i<7;i++) //将 led 左移一位
{
LED_PORT=_crol_(LED_PORT,1);
delay_10us(50000);
}
}
}
实现流水灯左右循环
其实和上面方法同理,这里使用了keil内置的位移库函数,左移是_crol_(),右移是_cror_()。
#include "reg52.h"
#include "intrins.h"
#define LED_PORT P2 //使用宏定义P2端口
typedef unsigned int u16;
typedef unsigned char u8;
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
u8 i=0;
LED_PORT=~0x01;
delay_10us(50000);
while(1)
{
for(i=0;i<7;i++) //将 led 左移一位
{
LED_PORT=_crol_(LED_PORT,1);
delay_10us(50000);
}
for(i=0;i<7;i++) //将 led 右移一位
{
LED_PORT=_cror_(LED_PORT,1);
delay_10us(50000);
}
}
}