Skip to main content
Associate II
December 25, 2025
Solved

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

  • December 25, 2025
  • 3 replies
  • 533 views

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.

Best answer by AScha.3

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

 

3 replies

TDK
Super User
December 25, 2025

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
Chief III
December 25, 2025

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
December 25, 2025

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 ""Accept as Solution""."
BaldrickAuthor
Associate II
December 25, 2025

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
December 26, 2025

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 ""Accept as Solution""."