這里要用到一定的模電知識。電容兩端電壓不能突變,電感兩端電流不能突變。這里利用了電容的放電延時實現硬件消抖。按鍵按下會有抖動,波形有毛刺,使得高低電平顯現不明顯,而按鍵按下時,電容放電一下,馬上又被充電,此時電容兩端的電壓不會突然變化,這個延時時間恰好可以達到消抖作用。
這里需要使用一個固件庫函數:
/** * @brief Reads the specified input port pin. * @param GPIOx: where x can be (A..K) to select the GPIO peripheral for STM32F405xx/407xx and STM32F415xx/417xx devices * x can be (A..I) to select the GPIO peripheral for STM32F42xxx/43xxx devices. * x can be (A, B, C, D and H) to select the GPIO peripheral for STM32F401xx devices. * @param GPIO_Pin: specifies the port bit to read. * This parameter can be GPIO_Pin_x where x can be (0..15). * @retval The input port pin value. */ uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) { uint8_t bitstatus = 0x00; /* Check the parameters */ assert_param(IS_GPIO_ALL_PERIPH(GPIOx)); assert_param(IS_GET_GPIO_PIN(GPIO_Pin)); if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)Bit_RESET) { bitstatus = (uint8_t)Bit_SET; } else { bitstatus = (uint8_t)Bit_RESET; } return bitstatus; }
在第一次使用這個函數的時候,我沒有理解到位,一看到定義bitstatus=0x00,就以為返回的是個八位端口的值,其實這個返回值只有0或者1兩種結果。
/**
* @brief GPIO Bit SET and Bit RESET enumeration
*/
typedef enum
{
Bit_RESET = 0,
Bit_SET
}BitAction;
在這個枚舉中,可以知道,讀取IO的數據只可能是0或者1。