#define uint unsigned int
#define uchar unsigned char
void delay_ms(uint)
sbit led0=P0^0
sbit led1=P0^1
sbit key1=P3^2
sbit key2=P3^3
void main()
{
uchar i=0
uchar j=0
while(1)
{
if(key1==0)//按键1
{
delay_ms(10)
if(key1==0)
{
i++
i=i%2
switch(i)
{
case 0: led0=1 break//关小灯
case 1: led0=0 break//开小灯
default: break
}
}
while(!key1)
}
if(key2==0)//按键2
{
delay_ms(10)
if(key2==0)
{
j++
j=j%2
switch(j)
{
case 0: led1=1 break//关小灯
case 1: led1=0 break//开小灯
default: break
}
}
while(!key2)
}
}
}
void delay_ms(uint z) //延时子程序
{
uint x,y
for(x=zx>0x--)
for(y=110y>0y--)
}
下面是用C51编写的简单程序:#include <reg51.h>
#include <intrins.h>
sbit io_Key = P1 ^ 1
sbit led1 = P1 ^ 2
sbit led2 = P1 ^ 3
sbit led3 = P1 ^ 4
unsigned char ucCount = 0
bit flag05s = 0
//---------------------------------
void delay125us(void) //@12.000MHz
{
unsigned char i
i = 60
while (--i)
}
void Timer0Init(void) //10毫秒@12MHz
{
TMOD &= 0xF0 //设置定时器模式
TMOD |= 0x01 //设置定时器模式
TL0 = 0xF0 //设置定时初值
TH0 = 0xD8 //设置定时初值
TR0 = 1 //开定时器0
ET0 = 1//开定时器0中断
EA = 1 //开总中断
}
//T0中断用来计数器溢出
void zd0(void) interrupt 1
{
TL0 = 0xF0 //设置定时初值
TH0 = 0xD8 //设置定时初值
if(++ucCount >= 50)
{
ucCount = 0
flag05s = 1//g_flag05s = isYes定时0.52秒到,用于测量周期延时
}
}
void main(void)
{
unsigned char CountTemp = 0, ucState = 0
Timer0Init()
while(1)
{
//-------------------------------
//简单的按键检测程序:
io_Key = 1
_nop_()
if( io_Key == 0 )
{
CountTemp = 0
do
{
delay125us()
if( io_Key != 0 ) break
} while(++CountTemp >160)// 延时20ms去抖动
if(CountTemp >160)//如果按键时间有效,改变状态
{
switch(ucState)
{
case(0):
{
ucState = 1
led1 = 0
led2 = 0
led3 = 0
}
break
case(1):
{
ucState = 2
led1 = 0
led2 = 0
led3 = 0
}
break
case(2):
{
ucState = 0
led1 = 0
led2 = 1
led3 = 1
}
break
}
while(io_Key == 0) //等待按键释放
}
}
//------------------------------
//每0.5秒改变一下LED状态
if(flag05s == 1)
{
flag05s = 0
switch(ucState)
{
case(0):
{
led1 = !led1
led2 = !led2
led3 = !led3
}
break
case(1):
{
bit ledTemp = led1
led1 = led2
led2 = led3
led3 = ledTemp
}
break
//LED常亮可以忽略改变LED状态
/*
case(2):
{
led1 = 0
led2 = 0
led3 = 0
}
break
*/
}
}
}
}
//-----------------------------------------------
//上面程序中有很多地方可以优化,这里只是给出一个参考供学习。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)