Home | Projects | Notes > MCU Peripheral Drivers > GPIO Application 2: Toggling On-board LED with On-board Button (gpio_02_led_toggle_with_button.c)
gpio_02_led_toggle_with_button.c)
Write a program to toggle the on-board LED whenever the on-board button is pressed.
In the case of STM32F407 Discovery board, when the user button is pressed, the GPIO pin connected to it is pulled to HIGH. (Check the schematic of the board. It is board specific!)
gpio_02_led_toggle_with_button.cPath: Project/Src/
xxxxxxxxxx611/*******************************************************************************2 * File : gpio_02_led_toggle_with_button.c3 * Brief : Program to toggle the on-board LED whenever the on-board button is4 * pressed5 * Author : Kyungjae Lee6 * Date : May 23, 20237 ******************************************************************************/8
910
1112/* This is not universal. Check the board schematic */13
14/**15 * delay()16 * Brief : Spinlock delays the program execution17 * Param : None18 * Retval : None19 * Note : N/A20 */21void delay(void)22{23 /* Appoximately ~200ms delay when the system clock freq is 16 MHz */24 for (uint32_t i = 0; i < 500000 / 2; i++);25} /* End of delay */26
27
28int main(int argc, char *argv[])29{30 GPIO_Handle_TypeDef GPIOLed, GPIOBtn;31
32 /* GPIOLed configuration */33 GPIOLed.pGPIOx = GPIOD;34 GPIOLed.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_12;35 GPIOLed.GPIO_PinConfig.GPIO_PinMode = GPIO_PIN_MODE_OUT;36 GPIOLed.GPIO_PinConfig.GPIO_PinSpeed = GPIO_PIN_OUT_SPEED_HIGH;37 GPIOLed.GPIO_PinConfig.GPIO_PinOutType = GPIO_PIN_OUT_TYPE_PP;38 GPIOLed.GPIO_PinConfig.GPIO_PinPuPdControl = GPIO_PIN_NO_PUPD;39 GPIO_Init(&GPIOLed);40
41 /* GPIOBtn configuration */42 GPIOBtn.pGPIOx = GPIOA;43 GPIOBtn.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_0;44 GPIOBtn.GPIO_PinConfig.GPIO_PinMode = GPIO_PIN_MODE_IN;45 GPIOBtn.GPIO_PinConfig.GPIO_PinSpeed = GPIO_PIN_OUT_SPEED_HIGH; /* Doesn't matter */46 //GPIOBtn.GPIO_PinConfig.GPIO_PinOutType = GPIO_PIN_OUT_TYPE_PP; /* N/A */47 GPIOBtn.GPIO_PinConfig.GPIO_PinPuPdControl = GPIO_PIN_NO_PUPD;48 /* External pull-down resistor is already present (see the schematic) */49 GPIO_Init(&GPIOBtn);50
51 while (1)52 {53 if (GPIO_ReadFromInputPin(GPIOBtn.pGPIOx, GPIOBtn.GPIO_PinConfig.GPIO_PinNumber) == BTN_PRESSED)54 {55 delay(); /* Introduce debouncing time */56 GPIO_ToggleOutputPin(GPIOLed.pGPIOx, GPIOLed.GPIO_PinConfig.GPIO_PinNumber);57 }58 }59
60 return 0;61} /* End of main */