diff --git a/Inc/general_gpio.h b/Inc/general_gpio.h index 425502d..553af0f 100644 --- a/Inc/general_gpio.h +++ b/Inc/general_gpio.h @@ -94,7 +94,7 @@ typedef struct uint32_t Sw_Pin; ///< GPIO пин ножки кнопки uint8_t Sw_ActiveLvl; ///< Активный уровень ножки (при котором кнопка нажата) - uint32_t Sw_PrevState; ///< Предыдущее состояние кнопки + uint32_t Sw_CurrentState; ///< Текущее состояние кнопки uint32_t Sw_FilterDelay; ///< Фильтр от дребезга (в мс) uint32_t tickprev; diff --git a/Src/general_gpio.c b/Src/general_gpio.c index a431b4d..a0a6a00 100644 --- a/Src/general_gpio.c +++ b/Src/general_gpio.c @@ -280,47 +280,37 @@ int GPIO_Read_Switch(GPIO_SwitchTypeDef *sw) if(check_null_ptr_3(sw, sw->Sw_Port, sw->Sw_Pin)) return -1; - if(HAL_GPIO_ReadPin(sw->Sw_Port, sw->Sw_Pin) == sw->Sw_ActiveLvl) + int current_level = (HAL_GPIO_ReadPin(sw->Sw_Port, sw->Sw_Pin) == sw->Sw_ActiveLvl); + + if(sw->Sw_FilterDelay) // если включена защита от дребезга { - sw->Sw_PrevState = 1; - - - if(sw->Sw_FilterDelay) // если включена защита от дребезга + // Если таймер не запущен и состояние изменилось - запускаем таймер + if(sw->tickprev == 0 && current_level != sw->Sw_CurrentState) { - if(sw->tickprev == 0) - sw->tickprev = local_time(); + sw->tickprev = local_time(); + } + // Если таймер запущен + if(sw->tickprev != 0) + { + // Проверяем, прошел ли достаточный интервал для фильтрации if((local_time() - sw->tickprev) >= sw->Sw_FilterDelay) { - if(HAL_GPIO_ReadPin(sw->Sw_Port, sw->Sw_Pin) == sw->Sw_ActiveLvl) + // Обновляем состояние только если оно все еще отличается + if(current_level != sw->Sw_CurrentState) { - return 1; + sw->Sw_CurrentState = current_level; } - else - { - sw->tickprev = 0; - return 0; - } - } - } - else // если нет защиты от дребезга - { - if(HAL_GPIO_ReadPin(sw->Sw_Port, sw->Sw_Pin) == sw->Sw_ActiveLvl) - { - return 1; - } - else - { + // Останавливаем таймер в любом случае sw->tickprev = 0; - return 0; } } } - else + else // если нет защиты от дребезга { - sw->Sw_PrevState = 0; + sw->Sw_CurrentState = current_level; } - return 0; + return sw->Sw_CurrentState; } //------------------------GPIO SW FUNCTIONS------------------------- //------------------------------------------------------------------- \ No newline at end of file