cancel
Showing results for 
Search instead for 
Did you mean: 

The HAL function to read the current output status of a GPIO

diverger
Associate III
Posted on September 13, 2017 at 08:24

If I configure one GPIO pin to output. Is there a function in HAL to read back the current output status of it?

1 ACCEPTED SOLUTION

Accepted Solutions
David SIORPAES
ST Employee
Posted on September 13, 2017 at 18:20

You can use HAL_GPIO_ReadPin().

Even if the pin is set to output the IDR register will give you its current output status.

0690X00000608E0QAI.png

View solution in original post

12 REPLIES 12
David SIORPAES
ST Employee
Posted on September 13, 2017 at 18:20

You can use HAL_GPIO_ReadPin().

Even if the pin is set to output the IDR register will give you its current output status.

0690X00000608E0QAI.png

It is not true. If a pin is configured as open-drain output and its ODR bit value is 1, it may be pulled down externally. Then its IDR bit is 0, but ODR bit still is 1. So, HAL_GPIO_ReadPin will return 0 while output state is 1.

Well spotted, @hdmi87​ , even if this is a rather old thread, it's always good to correct a mistake.

It appears that there's no function in Cube/HAL to read GPIO_ODR, it appears that the pin-toggling function is the only one which mentions ODR at all.

OTOH, reading back ODR has a relatively rare usage. Cube/HAL, as inevitably every "library" does, implements only a subset of possible functionality, and of course that subset is based on the "most often used" functionality. I'd leave this to simply reading the register.

JW

Hi,

Thanks for your attention to such an old question from me.

Yes. Though it is wired, in a project I had to do this​. So, if I'm sure the output pin is not configured as OD, the method David proposed should work, right?

Best​ regards.

Diverger​

remco2
Associate II

If you just want to read back what you wrote to the pin, you can check whether GPIOx->BSRR is GPIO_PIN_RESET or GPIO_PIN_SET.

Have you actually tried this?

GPIOx_BSRR are write-only and read-as-zero.

0693W00000QO7yeQAD.pngTo find out the state of output register, read, well, the output register, i.e. GPIOx_ODR.

JW

I wouldn't answer a 4 year old question with a mind experiment so yes, I've tried it and it works.

On which STM32 and how exactly?

JW

As the BSRR is a write only register, even if it does read something, it is not guaranteed to be correct. And there ir no sense in doing it anyway, because it doesn't have any advantage over reading the ODR register.