/**
  ******************************************************************************
  * @file     Key_scan.c
  * @author   SINOMCU-AE
  * @brief    key scan
  *    
  *          This file provides functions to scan GPIO KEY;
  *         
  ******************************************************************************
  * @attention 
  *                           DISCLAIMER
  * The present firmware which is for guidance only aims at providing customers
  * with coding information regarding their products in order for them to save
  * time. As a result, SinoMCU shall not be held liable for any direct,indirect
  * or consequential damages with respect to any claims arising from the content 
  * of such firmware and/or the use made by customers of the coding information 
  * contained herein in connection with their products.
  *
  * <h2><center>&copy; Copyright (c) 2021 sinomcu All rights reserved.</center></h2>
  *
  ******************************************************************************
  */

#include "Key_scan.h"
#include "SysTick_Delay.h"
#include "GPIO_CFG.h"

/**
  * @brief  Scan_Key program
  * @param  None
  * @retval return key effective or not
  */
uint8_t Scan_Key(void)
{
  static uint8_t KEY_Jitter_count = 0;                     // 消抖计数
  static uint8_t key_pin_pre_state = KEY_RELEASE_UP;       // 按键引脚前一状态,未消抖
  uint8_t key_pin_cur_state = KEY_RELEASE_UP;              // 按键引脚当前状态,未消抖
  
  static uint8_t key_value_pre = KEY_RELEASE_UP;           // 按键消抖后,前一有效值  
  uint8_t key_value_cur = KEY_NULL;                        // 按键消抖后,当前有效值 
  
  uint8_t key_return = KEY_NULL;                           // 按键返回值

  if(Get_State_10MS_SF_Timer() == SF_TIMER_OV)             // 10ms扫描一次pin
  {
    Start_10MS_SF_Timer();                                 // clear sf_timer_ov

    key_pin_cur_state =Read_Key_pin();                     // 读引脚状态

    if(key_pin_pre_state != key_pin_cur_state)             // 按键引脚状态改变,重新消抖
    {
      key_pin_pre_state = key_pin_cur_state;
      KEY_Jitter_count =0;    
    }
    else
    {
      KEY_Jitter_count ++;                                 // 消抖中
    }

    if( KEY_Jitter_count > KEY_JITTER_NUM)                 // 消抖KEY_JITTER_NUM次数达到,消抖完成
    {
      KEY_Jitter_count = 0;
      key_value_cur = key_pin_cur_state;

      if(key_value_pre != key_value_cur)                   // 按键消抖后,有效值变化;不连按
      {
        key_value_pre = key_value_cur;
        if(key_value_cur == KEY_PRESS_DOWN)   
        {
          key_return = KEY_EFFECTIVE;                      // 按下有效
        }
        else                                   
        {
          //key_return = KEY_EFFECTIVE;                      // 抬起有效,按下和抬起,选择其中一种
        }
      }
      else                                                 // 连按,未处理
      {
        ;
      }
    }
  }
  return key_return;
}

/******************************** END OF FILE *********************************/
