【C语言】单片机上的按键检测框架

    又好久没来写blog,最近在做项目发现之前写的stm32操作都忘了,还好做了个记录,回来看了下很多忘了的就又知道怎么做了。

    下面是我之前写的一个按键检测的框架,适合比较多的按键操作,从信号接收、滤波、最好处理按键任务,大体上没什么问题,不过没具体测试过到时可能会有bug。

  1 /******************************************************************************
  2 * @file    button.c
  3 * @author  wule
  4 * @version 
  5 * @date    
  6 * @brief   
  7 ******************************************************************************
  8 *
  9 *****************************************************************************/
 10 
 11 typedef unsigned char ButtonSizeType;
 12 
 13 typedef enum{
 14                 RESET = 0,
 15                 SET = !RESET,
 16             }FLAG;
 17 
 18 typedef struct button_bit{
 19     ButtonSizeType button1:1;
 20     ButtonSizeType button2:1;
 21     ButtonSizeType button3:1;
 22     ButtonSizeType button4:1;
 23     ButtonSizeType button5:1;
 24     ButtonSizeType button6:1;
 25     ButtonSizeType button7:1;
 26     ButtonSizeType button8:1;
 27 }ButtonBitType;
 28 
 29 typedef union
 30 {
 31     ButtonBitType button_bit;
 32     ButtonSizeType button;
 33 }ButtonType;
 34 
 35 ButtonType InputFlag;
 36 
 37 //初始化按键标志状态
 38 void Init_Button_Variable(void)
 39 {
 40     InputFlag.button = 0;
 41 }
 42 
 43 //判断函数,读取每个按键的状态
 44 ButtonSizeType ReadButtonBit(void)
 45 {
 46     ButtonType button_bit;
 47     
 48     button_bit.button = 0;
 49     
 50     button_bit.button_bit.button1 = 1;
 51     button_bit.button_bit.button3 = 1;
 52     button_bit.button_bit.button5 = 1;
 53     
 54     return button_bit.button;
 55 }
 56 //滤波,返回值代表当前按键的值
 57 ButtonSizeType Button_Filter(void)
 58 {
 59     ButtonSizeType bf_buf;
 60     static ButtonSizeType bf_pre_buf = 0,bf_backval = 0;
 61     static unsigned char bf_filtercnt = 0;
 62     
 63     bf_buf = ReadButtonBit();
 64 
 65     if(bf_buf != bf_backval && bf_buf == bf_pre_buf)//判断两次是否相同
 66     {
 67         bf_filtercnt ++;
 68         if(bf_filtercnt > 50)//作一个简单的滤波
 69         {
 70             bf_backval = bf_pre_buf;
 71         }
 72     }
 73     else
 74     {
 75         bf_pre_buf = bf_buf;
 76         bf_filtercnt = 0;
 77     }
 78     
 79     return bf_backval;
 80 }
 81 //处在一个时间可控的位置,这里可以实现各种按键的操作
 82 void ButtonTask(void)
 83 {
 84     ButtonType bt_state = Button_Filter();//得到按键状态
 85     
 86     if(InputFlag.button_bit.button1 == 0 && bt_state.button_bit.button1 == 1)
 87     {
 88         //单次触发
 89     }
 90     else if(InputFlag.button_bit.button1 == 1 && bt_state.button_bit.button1 == 0)
 91     {
 92         //单次释放
 93     }
 94     
 95     
 96     if(bt_state.button_bit.button1 == 1)
 97     {
 98         //计时触发
 99     }
100     else
101     {
102         //结束判断按的时间
103     }
104 }

 

posted @ 2014-03-12 16:09  吾乐  阅读(1844)  评论(0编辑  收藏  举报