Reading Buttons on Nucleo-F401RE (SW4STM32 and STM32CubeMX)

In previous posts I wrote about blinking LED and configuring ports. Now it is time to read some buttons.

First we need to generate project in CubeMX, we need to select board as in our Blinky example (I will explain later why we are selecting Nucleo board and not our specific microcontroller):

Next we need to set project settings:

Now we need to generate program (Menu -> Project -> Generate Code) and click on Open Project and now we are ready in SW4STM32 to start coding.

First we need to check if everything is ready. We Build our program (by clicking on hammer on toolbar. We need to get something like …Build finished… in console.

As we can see here, the blue button is connected to pin 13 of PORT C:

We need to configure this pin to be input, internal pull-up resitor is not needed because there is one on the board outside of microcontroller. If you look you can also see R29 and C15 which are used for debouncing.

We need some kind of feedback of button reading so we will be using main.c from Blinky example.

You can copy above code and replace main function in main.c if you haven’t gone through blinky example. Build and test program, Green LED should blink with one second interval. And now we start our program for reading Button.

We need to start clock for PORTC, we do this by changing user code 1 in main.c to:

We also need to add one more line for pin initialization:

And we need to set pin registers:

B1-Pin and B1_GPIO_Port are fixed values set by CubeMX and are written in main.h under inc folder of our project:

They are added by CubeMX. They are added because we selected Nucleo board when we selected new project. If we would be starting new project just by selecting our microcontroller from list, then this defines would not be here.

We also need to replace program inside while() loop in main.c so that LED would show us the button state.

If you look at this picture you see that LED lights when output is high, but if you check higher up, yo see that by pushing button we pul the input low. This means that if the input is low then button is pressed and LED output must be high and vise versa.

We do this with these few commands:

To explain these few lines of code:

-first in the line with if statement we check if the pin input is high. If it is, that means that button is not pressed.

-so in next line we “RESET” output to LED.

-if pin input is low, then the first statement inside brackets is not true and the statement after else runs and this one “SETS” LED output and LED light up.

This concludes our input reading example.