1、新建工程
2、编写程序
1)引用代码
在LED灯闪烁的代码基础上进行修改,LED灯闪烁的代码如下:
#include <STC89C5xRC.H>
#include <INTRINS.H>
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main()
{
while(1)
{
P2=0xFE;//1111 1110
Delay500ms();
P2=0xFF;//1111 1111
Delay500ms();
}
}
2)延时亮灭
如果要延时亮灭,则把P2从第一个灯亮P2=0xFE;//1111 1110,再到第二个灯亮P2=0xFD;//1111 1101,以此类推进行循环,见下图:
#include <STC89C5xRC.H>
#include <INTRINS.H>
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main()
{
while(1)
{
P2=0xFE;//1111 1110
Delay500ms();
P2=0xFD;//1111 1101
Delay500ms();
P2=0xFB;//1111 1011
Delay500ms();
P2=0xF7;//1111 0111
Delay500ms();
P2=0xEF;//1110 1111
Delay500ms();
P2=0xDF;//1101 1111
Delay500ms();
P2=0xBF;//1011 1111
Delay500ms();
P2=0x7F;//0111 1111
Delay500ms();
}
}
3)编译、下载
打开文件,然后点击下载,再打开开关上电。

成功!
4)优化
想要代码变的灵活,比如200毫秒流水闪烁的话,最好是做个形参,接下来我们把延时函数设置成1毫秒:
#include <STC89C5xRC.H>
#include <INTRINS.H>
void Delay1ms(unsigned int xms) //@11.0592MHz
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
xms--£» //xms=xms-1
}
}
void main()
{
while(1)
{
P2=0xFE;//1111 1110
Delay1ms(1000);
P2=0xFD;//1111 1101
Delay1ms(1000);
P2=0xFB;//1111 1011
Delay1ms(100);
P2=0xF7;//1111 0111
Delay1ms(100);
P2=0xEF;//1110 1111
Delay1ms(100);
P2=0xDF;//1101 1111
Delay1ms(100);
P2=0xBF;//1011 1111
Delay1ms(100);
P2=0x7F;//0111 1111
Delay1ms(100);
}
}

不知道为什么我设置小了参数,流水灯还是以500毫秒的速度流水闪烁,后面再查找一下原因吧!有高手知道也请指出不胜感谢!
3424

被折叠的 条评论
为什么被折叠?



