STC15單片機按鍵控制流水燈方向,按鍵1,流水燈左移;按鍵2,流水燈右移。
單片機源程序如下:- #include <reg51.h>
- unsigned char ucLed = 1;
- unsigned char ucKey_State = 0;
- // 延時函數(shù)(最小約1ms@12MHz)
- void Delay(unsigned int uiNum)
- {
- unsigned int i;
- while(uiNum--)
- for(i=0; i<628; i++);
- }
- // 按鍵處理:SW1-0x10, SW2-0x20, SW3-0x40, SW4-0x80
- void Key_Proc(void)
- {
- unsigned char ucKey_Value = 0;
- P0 |= 0xf0;
- if((P0 & 0xf0) != 0xf0) // 按鍵按下
- {
- Delay(10); // 延時消抖
- if((P0 & 0xf0) != 0xf0) // 按鍵按下
- ucKey_Value = ~P0 & 0xf0; // 讀取鍵值
- }
- if(ucKey_Value != ucKey_State)// 鍵值改變
- ucKey_State = ucKey_Value; // 保存鍵值
- else
- ucKey_Value = 0; // 清除鍵值
- switch(ucKey_Value)
- {
- case 0x10: // SW1按下
- ucLed <<= 1; // 左移
- if(ucLed == 0x10) // LED4亮后
- ucLed = 1; // LED1亮
- break;
- case 0x20: // SW2按下
- ucLed >>= 1; // 右移
- if(ucLed == 0) // LED1亮后
- ucLed = 8; // LED4亮
- }
- P0 = ~ucLed;
- }
- // 主函數(shù)
- void main(void)
- {
- while(1)
- {
- Key_Proc();
- }
- }
復制代碼
|