C51--LED灯

1、点亮LED:
看电路板原理图,找到对应LED的接口位置

#include "reg52.h"

sbit ledOne = P3^7;
sbit ledTwo = P3^6;

void main()
{
	ledOne = 0;
	//灯会亮,给P3.7口低电平
	ledTwo = 0;
	//灯会亮,给P3.6口低电平
}

2、LED闪烁
亮输出0;灭输出1。

#include "reg52.h"

sbit ledOne = P3^7;
sbit ledTwo = P3^6;

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){
		ledOne = 0;
		//灯会亮,给P3.7口低电平0;灯灭,给P3.7口高电平1
		Delay500ms();
		//数数,相当于延时,在此期间维持低(高)电平灯亮(灭)
		ledOne = 1;
		Delay500ms();

		ledTwo = 0;
		//灯会亮,给P3.6口低电平0;灯灭,给P3.6口高电平1
		Delay500ms();
		ledTwo = 1;
		Delay500ms();
	}
	
}

3、按键控制灯

ledOne = !ledOne; //一个按键控制,取反自己

#include "reg52.h"

sbit key1 = P2^1;
sbit ledOne = P3^7;

void main()
{
	//查询法检测开关是否被按下
	while(1){
			if(key1 == 0){	//key与gnd接通,低电平,值为0
				ledOne = 0;
				//灯会亮,给P3.7口低电平
				//ledOne = !ledOne;	//一个按键控制,取反自己
			}
		}
}

4、两个按键控制灯

#include "reg52.h"

sbit key1 = P2^1;
sbit key2 = P2^0;
sbit ledOne = P3^7;

void main()
{
	//查询法检测开关是否被按下
	while(1){
			if(key1 == 0){	//key与gnd接通,低电平,值为0
				ledOne = 0;
				//灯会亮,给P3.7口低电平
			}
			if(key2 == 0){	//key与gnd接通,低电平,值为0
				ledOne = 1;
				//灯会灭,给P3.7口高电平
			}
		}
}

5、消除抖动
nop();用到头文件:#include

#include "reg52.h"
#include 

sbit key1 = P2^1;
sbit key2 = P2^0;
sbit ledOne = P3^7;

void Delay50ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 3;
	j = 26;
	k = 223;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}



void main()
{
	//查询法检测开关是否被按下
	while(1){
			if(key1 == 0){	//key与gnd接通,低电平,值为0
				//延迟50ms再次判断
				//软件消除抖动
				Delay50ms();
				if(key1 == 0){
					ledOne = 0;
					//灯会亮,给P3.7口低电平
				}
				
			}
			if(key2 == 0){	//key与gnd接通,低电平,值为0
				//延迟50ms再次判断
				//软件消除抖动
				Delay50ms();
				if(key2 == 0){
					ledOne = 1;
					//灯会灭,给P3.7口高电平
				}
			}
		}
}

6、记录状态位来控制灯:
#define OFF 0
#define ON 1

#include "reg52.h"
#include 

#define ON  0
#define OFF 1

sbit key1 = P2^1;
sbit key2 = P2^0;
sbit ledOne = P3^7;

void Delay50ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 3;
	j = 26;
	k = 223;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}



void main()
{
	int ledMark = OFF;
	ledOne = 1;
	
	//查询法检测开关是否被按下
	while(1){
			if(key1 == 0){	//key与gnd接通,低电平,值为0
				//延迟50ms再次判断
				//软件消除抖动
				Delay50ms();
				if(key1 == 0){
					ledMark = ON;
				}
				
			}
			if(key2 == 0){	//key与gnd接通,低电平,值为0
				//延迟50ms再次判断
				//软件消除抖动
				Delay50ms();
				if(key2 == 0){
					ledMark = OFF;
				}
				if(ledMark == OFF){
					ledOne = 1;
				}else{
						ledOne = 0;
					}
			}
		}
}

你可能感兴趣的:(STC51,单片机,嵌入式硬件)