Step 2: Configure GPIO Pins
#define LED1_Pin GPIO_PIN_2
#define LED1_GPIO_Port GPIOA
#define LED2_Pin GPIO_PIN_3
#define LED2_GPIO_Port GPIOA
In the Project Explorer pane, expand the “Src” folder and open the “main.c” file. Scroll down to the main()
function and add the following code to configure the GPIO pins:
/* Configure GPIO pins */
__HAL_RCC_GPIOA_CLK_ENABLE(); // Enable GPIOA clock
GPIO_InitTypeDef GPIO_InitStruct; // GPIO configuration structure
GPIO_InitStruct.Pin = GPIO_PIN_2; // Use pin 2 on GPIOA
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; // Push-Pull output mode
GPIO_InitStruct.Pull = GPIO_NOPULL; // No pull-up or pull-down resistors
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; // Low speed
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); // Initialize GPIOA with settings
This code configures pin 2 on GPIOA as a push-pull output pin with no pull-up or pull-down resistors and low output speed.
Blink the LED using HAL_GPIO_WritePin
Add the following code inside the while(1)
loop to blink the LED:
/* Blink LED */
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_SET); // Turn LED on
HAL_Delay(1000); // Wait for 1 second
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET); // Turn LED off
HAL_Delay(1000); // Wait for 1 second
This code turns the LED on by setting the state of pin 2 on GPIOA to high, waits for 1 second, turns the LED off by setting the state of pin 2 on GPIOA to low, and then waits for 1 second again. This creates a blinking effect.
Blink the LED using HAL_GPIO_TogglePin
/* Blink LED */
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_2); // Toggle the state of the LED
HAL_Delay(1000); // Wait for 1 second
This code toggles the state of pin 2 on GPIOA (which is connected to an LED on the Mini STM32 board) and then waits for 1 second before toggling it again. This creates a blinking effect.
HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
HAL_Delay(1000);
HAL_GPIO_TogglePin(LED2_GPIO_Port, LED2_Pin);
Code to Blink both LED’s
HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
HAL_Delay(1000);
HAL_GPIO_TogglePin(LED2_GPIO_Port, LED2_Pin);
The first line toggles the state of an LED connected to the LED1_GPIO_Port and LED1_Pin. The second line waits for 1000 milliseconds (1 second) using the HAL_Delay() function. The third line toggles the state of another LED connected to the LED2_GPIO_Port and LED2_Pin.
Leave a Reply