In this tutorial, I will explain how to configure pin as an
input from button. I will use user button which connected to PA0.
First, make new project called button or whatever you want.
If you don’t know how to make a new project, you can learn from tutorial 2.
After that don’t forget to include the library for this project.
#include "stm32f4xx.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_gpio.h"
Every time you want to use GPIO, you must configure RCC (Reset and Clock Control) for each GPIO.
// Enable peripheral clock to GPIOA module RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); // Enable peripheral clock to GPIOD module RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef is a struct which used for input initialization value for GPIO.
// This is struct for configure GPIO GPIO_InitTypeDef GPIO_InitStruct;
User button is connected to PA0 therefore you have to configure PA0 as an input pin. This configuration is use built-in pull-down resistor.
// User button is connected to PA0 // So, configure PA0 as an input pin GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_DOWN;
Finally you have to initialize GPIOA with GPIO_Init function which takes two parameters. First is the GPIO to be initialized and second is the initialization value that we entered before to GPIO_InitStruct.
// GPIOA initialization GPIO_Init(GPIOA, &GPIO_InitStruct);LED 6 is used for output. So, configure PD15 as an output pin.
// Use LED 6 (blue) for output // So, configure PD15 as an output pin GPIO_InitStruct.GPIO_Pin = GPIO_Pin_15; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL; // GPIOD initialization GPIO_Init(GPIOD, &GPIO_InitStruct);
The initialization is done, now write the code for a simple program. When the user button is pressed, then LED 6 will turn on, otherwise the LED will turn off.
while (1) { // If button is pressed if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 1) { // Turn on LED 6 GPIO_SetBits(GPIOD, GPIO_Pin_15); } else { // Turn off LED 6 GPIO_ResetBits(GPIOD, GPIO_Pin_15); } }
Build and upload your code.
No comments :
Post a Comment