#include "stm32l0xx_hal.h"
static unsigned int MAX_TICKS = 3000;
/* Private variables */
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* 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
// Add timer tracking variables
uint32_t pressStartTime = 0;
GPIO_PinState previousButtonState = GPIO_PIN_SET; // Initialize as "not pressed"
while (1) {
// Read current button state
GPIO_PinState currentButtonState = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_5);
if (currentButtonState == GPIO_PIN_RESET) { // Button is pressed
// Detect rising edge (transition from not pressed to pressed)
if (previousButtonState == GPIO_PIN_SET) {
pressStartTime = HAL_GetTick(); // Record press start time
}
// Keep LED on only for first 3 seconds of press
if ((HAL_GetTick() - pressStartTime) < MAX_TICKS) {
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
}
} else { // Button is released
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
}
// Update previous button state
previousButtonState = currentButtonState;
}
}
static void MX_GPIO_Init(void) {
__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/pull-down
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; // Low speed
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
// Configure button pin (PB5) as input with pull-up resistor
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
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
// Initialize LED to be off
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
}