First read on GPIO configured as Digital Input reads wrong value
I am using STMCubeMX to generate HAL code to control the GPIO on a STM32L071Rb MCU.
I have set GPIO PA6 as "GPIO Input". The generated code initializes the GPIO by calling the function MX_GPIO_Init() where it "appears to be setting up the PA6 correctly".
This pin is pulled up on my PCB and reads properly under normal operating ocnditions.
However, the very first time that my program attempts to read this pin the HAL function returns a '0'. Subsequent calls to this same function and same pin return a '1'.
I copied the HAL code for reading a GPIO pin below. When I step through this code it looks like the first time for the PA6, the condition at line 8 FAILS and therefore the function returns the value GPIO_PIN_RESET. In the debugger, the value of GPIOx->IDR shows as 0x6000 and the value of GPIO_pin shows up as 0x40.
Do I need to take some extra steps in my initialization code such as: read all the GPIO once before starting any analysis, or change something in the STMCubeMx input configuration?
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
GPIO_PinState bitstatus;
/* Check the parameters */
assert_param(IS_GPIO_PIN_AVAILABLE(GPIOx,GPIO_Pin));
if((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
{
bitstatus = GPIO_PIN_SET;
}
else
{
bitstatus = GPIO_PIN_RESET;
}
return bitstatus;
}