Home > Software design >  STM32 Button Read
STM32 Button Read

Time:11-03

What is the difference between MODER's input mode and PUPDR. I saw some code parts for buttons. One code is like

GPIOB->MODER &= ~(3U << 2*4); // PB4
GPIOB->MODER |= (0U << 2*4);

and another code is,

GPIOB->MODER &= ~(3U << 2*8);  //PB8
GPIOB->PUPDR |= (2U << 2*8);

should I make MODER register as an input like first one? But second one is just clearing MODER register and making PUPDR as Pull-up.

shouldn't I making MODER as input first?

CodePudding user response:

The first code snippet, second line is doing nothing. Anything ORed with zero will keep its value.

In both snippets, the port is configured as an input by the first line. Pull-up/down is configured independently of the port mode, any port could be even configured as an output with pulls enabled (no idea why anyone would want it).

Internal pull is required if the circuit have no external one, to set the port level when button is not pressed.

The second snippet is setting pull-down for PB8, not pull-up. See snap from STM32F4 reference manual:

enter image description here

CodePudding user response:

To read a button on STM32, you should adjust the MODER as input. Then, you can just check the IDR(Input Data Register).

For PUPDR, you need this register if you do not have any externally connected Pull-up or pull-down resistor.

The second code assigns the specific port as input with pull-down configuration, in your example. So it is your decision to make it either pull-down or pull-up.

The first code is doing the same thing twice on the both lines.

  • Related