Skip to main content
Associate II
Dec 25, 2025 7:06 PM UTC
Solved

How to switch a port input<>output on the fly ?

Hi there

I'm a little embarrassed to post this, but..  Coming from Microchip world I would just change TRISx, so simple.

As I've learned so far the MX are in charge for setting up a port.

But in my application I need to set a 8 bit wide port for parallel interface to a device.

Also it needs to change output <> input.

My first thoughts were not to tell the MX about the device on port PC0 to PC7.

Then do the setup "manually" in the code.

But then again I think this so common, there must be a MX way of doing this.

 

Thank you.

AScha.3
AScha.3Best answer
Super User
Dec 25, 2025 8:36 PM UTC

So just write to the mode register...in or out .

And set in Cube the port as input, to avoid problems at startup with conflicting settings.

AScha3_0-1766694951335.png

 

If you feel a post has answered your question, please click on " Best Answer ".

6 replies

TDK
Dec 25, 2025 8:23 PM UTC

MX will initialize the port as either input or output depending on what you choose. That is all it can do. Do whatever you want with it after initialization. This includes switching between input and output using HAL_GPIO_Init.

If you are more familiar or prefer register access for any reason, modify the relevant bits of the GPIOC_MODER register directly. That is what actually controls the behavior of the chip. The reference manual has details on how this operates.

"If you feel a post has answered your question, please click ""Accept as Solution""."
MM..1
Super User
Dec 25, 2025 8:23 PM UTC

MX is designed for setup initial state , no dynamic. Then no.

But for be precise you can define alternate function peripheral , that have bidirectionals, but you need learn and place it on right pins before code use...

AScha.3
AScha.3Best answer
Super User
Dec 25, 2025 8:36 PM UTC

So just write to the mode register...in or out .

And set in Cube the port as input, to avoid problems at startup with conflicting settings.

AScha3_0-1766694951335.png

 

If you feel a post has answered your question, please click on " Best Answer ".
BaldrickAuthor
Associate II
Dec 25, 2025 10:06 PM UTC

Thank you.

I somehow knew there should be a more easy solution to this.

I assume I may also read/write directly to the port: IDR/ODR ?

AScha.3
Super User
Dec 26, 2025 5:57 AM UTC

Yes, a direct write to the port registers or read is the fastest way to get or set a port.

And if you want just set or reset one bit ( or more) then there is a register for setting and resetting bits in one single write access, just look at the port register description in RM.

If you feel a post has answered your question, please click on " Best Answer ".