51单片机 按键控制LED流水灯模式

本章博客实现按键控制LED流水灯模式的功能

1.将之前文件中Delay.c.h复制过来,进行添加

2.模块化编程

3.main.c

#include <REGX52.H>
#include "Timer0.h"
#include "Key.h"
#include <INTRINS.H>

unsigned char KeyNum,LEDMode;
void main()
{
		P2=0xFE;
		Timer0Init();
		while(1)
		{
			KeyNum=Key();

    if(KeyNum==1)
			{
				LEDMode++;
				if(LEDMode>=2)LEDMode=0;
			}
		}
	
}


void Timer0_Routine() interrupt 1  //中断函数
{
	static unsigned int  T0Count;
	TL0 = 0x18;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	T0Count++;
	if(T0Count>=500)
	{
		T0Count=0;
		//P2_0=~P2_0;
		if(LEDMode==0)
		P2=_crol_(P2,1);
		if(LEDMode==1)
		P2=_crol_(P2,1);

	}
	
}


4.在STC-ISP中可生成定时器计算器代码

 5.定时器部分

#include <REGX52.H>

void Timer0Init(void)		//1毫秒@12.000MHz
{
//	AUXR &= 0x7F;		//定时器时钟12T模式
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0x18;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
	ET0=  1;
	EA=1;
	PT0=0;
}

6.按键部分

#include <REGX52.H>
#include "Delay.h"

/**
		* @brief 获取独立按键键码
		*	@param 无
		* @retval 按下按键的键码,范围:0~4,无按键按下时返回值为0
    {
    }
		*/
		

unsigned char Key()
{
	unsigned char KeyNumber=0;
	if(P3_1==0){	Delay(20);while(P3_1==0);Delay(20);KeyNumber=1;}
	if(P3_0==0){	Delay(20);while(P3_0==0);Delay(20);KeyNumber=2;}
	if(P3_2==0){	Delay(20);while(P3_2==0);Delay(20);KeyNumber=3;}
	if(P3_3==0){	Delay(20);while(P3_3==0);Delay(20);KeyNumber=4;}

		return 	KeyNumber;
}


版权声明:本文为qf66668888原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。