Skip to main content
Vu.Andy
Associate III
September 28, 2016
Question

Changing GPIO pin from IN <> OUT dynamically?

  • September 28, 2016
  • 2 replies
  • 8842 views
Posted on September 29, 2016 at 01:50

What would be the best way to reconfigure a pin from Input to Output and vice versa on the flight?  The STM function HAL_GPIO_Init() is quite long so I would rather not use that function just to change a mode Input/Output.

What would be the most efficient way to change a pin I/O mode once it has been initially configured?

Thanks.

    This topic has been closed for replies.

    2 replies

    matic
    Associate III
    September 29, 2016
    Posted on September 29, 2016 at 06:45

    Directly in MODER register:

    From input to output:    GPIOx->MODER |= GPIO_MODER_MODERy_0;

    From output to input:    GPIOx->MODER &= ~(GPIO_MODER_MODERy);

    Where x means port (A, B, C,...) and y means pin number (0...15).

    Refer to GPIO MODER register in ref. manual.

    Walid FTITI_O
    Visitor II
    September 29, 2016
    Posted on September 29, 2016 at 12:16

    Hivu.andy,

    Some STM32Cube package are provided with Low level drivers which allows user to call LL macros for fast and/or partial instance/feature (re)configuration. For example with STM32F0 , STM32CubeF0 contains this LL drivers and you can call the following macros (located in stm32f0xx_ll_gpio.h)depending the GPIOs parameters that you want update: LL_GPIO_SetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Mode); LL_GPIO_SetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t PinMask, uint32_t OutputType); LL_GPIO_SetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Speed); LL_GPIO_SetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Pull); Otherwise, if the STM32Cube package still not supporting the LL drivers, you just call the GPIO_inti stuct with only updating the parameters that you will change like:

    /* -2- Configure IOs in output push-pull mode to drive external LEDs */
    GPIO_InitStruct.Pin = PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    HAL_GPIO_Init(GPIO_PORT, &GPIO_InitStruct);

    The direct access register code is another possible choice. -Hannibal-