⑴ 如何用单片机一个按钮开关控制3个灯3种效果。流水。闪烁。还有一直亮。用keil编程。
下面是用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;
*/
}
}
}
}
//-----------------------------------------------
//上面程序中有很多地方可以优化,这里只是给出一个参考供学习。