简单实现

先实现一个简单的程序,点亮一个LED灯

#include <at89c51RC2.h>

void main(){
	P2 = 0xFE;
}

选择创建HEX选项,然后按下F7运行一下代码

选择自己的单片机型号,我使用的是普中的STC89C52RC型号

烧录到单片机中,会发现第一个LED灯已经被点亮了

LED闪烁

#include <at89c51RC2.h>

void Delay500ms()		//@12.000MHz
{
	unsigned char i, j, k;

	_nop_();
	i = 4;
	j = 205;
	k = 187;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void main(){
    while(1){
        P2 = 0xFE;
        Delay500ms();
        P2 = 0xFF;
        Delay500ms();
    }
}

用一个延时函数来延时500毫秒,不然代码运行太快看不到效果,外部使用while无限循环

0xFE点亮第一个,FF是全部熄灭

再次烧录后第一个LED灯闪烁

8个LED灯循环

#include <at89c51RC2.h>
#include <INTRINS.H>

void Delay500ms()		//@12.000MHz
{
	unsigned char i, j, k;

	_nop_();
	i = 4;
	j = 205;
	k = 187;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}



void main(){
	while(1){
		P2 = 0xFE;
		Delay500ms();
		P2 = 0xFD;
		Delay500ms();
		P2 = 0xFB;
		Delay500ms();
		P2 = 0xF7;
		Delay500ms();
		P2 = 0xEF;
		Delay500ms();
		P2 = 0xDF;
		Delay500ms();
		P2 = 0xBF;
		Delay500ms();
		P2 = 0x7F;
		Delay500ms();
	}
}

再次烧录后,实现了8颗LED灯循环

 优化一下代码,自定义延时时间

#include <at89c51RC2.h>
#include <INTRINS.H>

void Delayms(unsigned int ms)		//@11.0592MHz
{
	unsigned char i, j;
	while(ms){
		i = 11;
		j = 190;
		do
		{
			while (--j);
		} while (--i);
		ms--;
	}
}

void main(){
	while(1){
		P2 = 0xFE;
		Delayms(1000);
		P2 = 0xFD;
		Delayms(1000);
		P2 = 0xFB;
		Delayms(200);
		P2 = 0xF7;
		Delayms(200);
		P2 = 0xEF;
		Delayms(200);
		P2 = 0xDF;
		Delayms(200);
		P2 = 0xBF;
		Delayms(200);
		P2 = 0x7F;
		Delayms(200);
	}
}

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐