#include "stm32l0xx_hal.h"
/* Private variables */
static uint32_t lastDebounceTime = 0; // Last time the button state changed
static const uint32_t debounceDelay = 50; // Debounce time in milliseconds
static uint8_t lastStableButtonState = GPIO_PIN_SET; // Assume button is not pressed initially
static uint8_t ledState = 0; // Track LED state (0=OFF, 1=ON)
/* Function prototypes */
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
int main(void) {
HAL_Init(); // Initialize HAL library
SystemClock_Config(); // Configure system clock
MX_GPIO_Init(); // Initialize GPIO
uint8_t lastButtonState = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_5); // Read initial button state
while (1) {
uint8_t currentButtonState = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_5); // Read current button state
// Check if button state has changed
if (currentButtonState != lastButtonState) {
lastDebounceTime = HAL_GetTick(); // Reset debouncing timer
}
// If the state has been stable for longer than the debounce delay
if ((HAL_GetTick() - lastDebounceTime) > debounceDelay) {
// If the stable state is different from the last stable state and button is pressed
if (currentButtonState != lastStableButtonState) {
lastStableButtonState = currentButtonState;
// If button is pressed (assuming active low: GPIO_PIN_RESET when pressed)
if (lastStableButtonState == GPIO_PIN_RESET) {
// Toggle LED state
ledState = !ledState;
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, ledState ? GPIO_PIN_SET : GPIO_PIN_RESET);
}
}
}
lastButtonState = currentButtonState; // Save current state for next comparison
}
}
// GPIO initialization function
static void MX_GPIO_Init(void) {
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOB_CLK_ENABLE(); // Enable GPIOB clock
// Configure LED pin (PB4) as output
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; // Push-pull output
GPIO_InitStruct.Pull = GPIO_NOPULL; // No pull-up or pull-down
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; // Low speed for LED
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
// Configure button pin (PB5) as input
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT; // Input mode
GPIO_InitStruct.Pull = GPIO_PULLUP; // Internal pull-up resistor
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; // Low speed for button
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
// Initialize LED to be off
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
}