标题: STC15单片机按键控制流水灯方向左移右移源程序 [打印本页]

作者: gaolixinca    时间: 2022-11-30 13:48
标题: STC15单片机按键控制流水灯方向左移右移源程序
STC15单片机按键控制流水灯方向,按键1,流水灯左移;按键2,流水灯右移。


单片机源程序如下:
  1. #include <reg51.h>
  2. unsigned char ucLed = 1;
  3. unsigned char ucKey_State = 0;
  4. // 延时函数(最小约1ms@12MHz)
  5. void Delay(unsigned int uiNum)
  6. {
  7.   unsigned int i;

  8.   while(uiNum--)
  9.     for(i=0; i<628; i++);
  10. }
  11. //  按键处理:SW1-0x10, SW2-0x20, SW3-0x40, SW4-0x80
  12. void Key_Proc(void)
  13. {
  14.   unsigned char ucKey_Value = 0;

  15.   P0 |= 0xf0;
  16.   if((P0 & 0xf0) != 0xf0)                                // 按键按下
  17.   {
  18.     Delay(10);                                                                        // 延时消抖
  19.     if((P0 & 0xf0) != 0xf0)                        // 按键按下
  20.       ucKey_Value = ~P0 & 0xf0;        // 读取键值
  21.   }
  22.   if(ucKey_Value != ucKey_State)// 键值改变
  23.     ucKey_State = ucKey_Value;        // 保存键值
  24.   else
  25.     ucKey_Value = 0;                                                // 清除键值

  26.   switch(ucKey_Value)
  27.   {
  28.     case 0x10:                                                                        // SW1按下
  29.       ucLed <<= 1;                                                        // 左移
  30.       if(ucLed == 0x10)                                        // LED4亮后
  31.         ucLed = 1;                                                        // LED1亮
  32.       break;
  33.     case 0x20:                                                                        // SW2按下
  34.       ucLed >>= 1;                                                        // 右移
  35.       if(ucLed == 0)                                                // LED1亮后
  36.         ucLed = 8;                                                        // LED4亮
  37.   }
  38.   P0 = ~ucLed;
  39. }
  40. // 主函数
  41. void main(void)
  42. {
  43.   while(1)
  44.   {
  45.     Key_Proc();
  46.   }
  47. }
复制代码







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1