⑴ 如何用單片機一個按鈕開關控制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;
*/
}
}
}
}
//-----------------------------------------------
//上面程序中有很多地方可以優化,這里只是給出一個參考供學習。