以下是模块化编程,各头文件已经设置在该程序同目录下(烧到板子上现象只有D1亮,没有向左流水灯的现象)
#include <REGX52.H>
#include <INTRINS.H>
#include "Key.h"
#include "Timer.h"
unsigned char KeyNum,LEDMode=0;
void main()
{
P2=0xFE;
Timer_Init();
while(1)
{
KeyNum=Key();
if(KeyNum==1)
{
LEDMode++;
if(LEDMode>=2)
LEDMode=0;
}
}
}
/*定时器中断函数*/
void Timer0_Routine() interrupt 1 //定时器0的中断号是interrupt 1
{
static unsigned char TimerNum; //静态全局变量
TMOD &= 0xF0; //定时器1ms后到中断函数会置零,所以重新赋值
TMOD |= 0x01;
TimerNum++;
if(TimerNum>=500) //500ms
{
TimerNum=0;
if(LEDMode==0) //按下K1流水灯反向
P2=_crol_(P2,1);
if(LEDMode==1)
P2=_cror_(P2,1);
}
}
#include <REGX52.H>
void Timer0_Init(void) //1毫秒@12.000MHz
{
TMOD &= 0xF0; //设置定时器模式 与置零,保留高四位(定时器1),第四位置零
TMOD |= 0x01; //设置定时器模式 或置一,保留高四位(定时器1),最低位置一
TL0 = 0x18; //设置定时初始值 64535到64535共1000微妙,即1毫秒
TH0 = 0xFC; //设置定时初始值 TL0=64535%257,TH0=64535/256
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
PT0=0;
}
#include <REGX52.H>
#include "Delay1ms.h"
unsigned char Key()
{
unsigned char KeyNum;
if(P1_4==0) {Delay1ms(20);while(P1_4==0);Delay1ms(20);KeyNum=1;}
if(P1_5==0) {Delay1ms(20);while(P1_5==0);Delay1ms(20);KeyNum=2;}
if(P1_6==0) {Delay1ms(20);while(P1_6==0);Delay1ms(20);KeyNum=3;}
if(P1_7==0) {Delay1ms(20);while(P1_7==0);Delay1ms(20);KeyNum=4;}
if(P3_5==0) {Delay1ms(20);while(P3_5==0);Delay1ms(20);KeyNum=5;}
return KeyNum;
void Delay1ms(unsigned char xms) //@12.000MHz
{
unsigned char data i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}