Skip to main content
Visitor II
January 5, 2022
Question

Strange behavior with call to HAL_GPIO_ReadPin()

  • January 5, 2022
  • 2 replies
  • 1459 views

I am seeing some strange happenings using X-CUBE-MEMS software pack, which generates some code for user buttons, LED outputs, etc.

I noticed the user button was always returning GPIO_PIN_SET even when it should be returning GPIO_PIN_RESET

I make a call like so:

PushButtonState = BSP_PB_GetState(BUTTON_KEY);

Which calls this function: (I've added some serial debug output)

int32_t BSP_PB_GetState(Button_TypeDef Button)
{
	GPIO_PinState bitstatus;
 bitstatus = (int32_t)(HAL_GPIO_ReadPin(BUTTON_PORT[Button], BUTTON_PIN[Button]) == GPIO_PIN_RESET);
	serprintf("After call: %i\n", bitstatus);
	return bitstatus;
}

Which calls this function (again with debug output added)

GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
 GPIO_PinState bitstatus;
 
 /* Check the parameters */
 assert_param(IS_GPIO_PIN(GPIO_Pin));
 
 if ((GPIOx->IDR & GPIO_Pin) != 0x00u)
 {
 bitstatus = GPIO_PIN_SET;
 }
 else
 {
 bitstatus = GPIO_PIN_RESET;
 }
	serprintf("Bitstatus: %i\n", bitstatus);
 return bitstatus;
}

HAL_GPIO_ReadPin is returning GPIO_PIN_RESET as expected, but the calling function doesn't seem to know that. My serial output looks like this:

Bitstatus: 0
After call: 1

What is happening here?

    This topic has been closed for replies.

    2 replies

    Super User
    January 5, 2022

    > bitstatus = (int32_t)(HAL_GPIO_ReadPin(BUTTON_PORT[Button], BUTTON_PIN[Button]) == GPIO_PIN_RESET);

    If HAL_GPIO_ReadPin returns GPIO_PIN_RESET (0), then this comparison evaluates true which returns 1.

    In other words, the return value from BSP_PB_GetState is opposite of the return value from HAL_GPIO_ReadPin.

    Edit:

    A search on GitHub shows your implementation is the opposite of what is there, at least on this instance:

    https://github.com/rajeev1986/ST25dv-sdk/blob/b0ff4ffadc361684b8c35aaddb3f2f340f0052df/Drivers/BSP/ST25-Discovery/st25dx_discovery.c#L362

     

    jgauthierAuthor
    Visitor II
    January 5, 2022

    Ah! I totally missed the comparison. Thanks for pointing that out.