Wednesday, August 10, 2016

Controlling the external LED with the STM32F4 Discovery Board


In this short tutorial I will show you how to toggle the external LED with the STM's built-in user button (the blue one in the picture above). Although it's very simple, it shows you some basics of controlling GPIO pins.

Things you need:
  • STM32F4 Discovery Board with the USB cable
  • Breadboard
  • Standard LED
  • Resistor (at least 1k Ohm)
  • 2 female/male jumper wires
  • 1 male/male jumper wire

1. Setting up the circuit

STM32F4 Breadboard Cable Color
PD5 Positive power rail (red) Orange
GND Negative power rail (blue) White

Connect the LED in series with the resistor and complete the circuit with the jumper wire (in my case green).

Note: Since all LEDs are polarized, the longer leg of the LED (the positive, anode pin) should be on the resistor's side (the right leg in the picture below).



2. Writing the code

The simplest way is to use STM32F4 standard GPIO library. The full code is available here. I will explain it step by step.

a) LED

Since our LED is connected to PD5 you have to enable GPIOD clock. 
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
Next configure the PD5 pin in output pushpull mode.
GPIO_InitTypeDef led;
led.GPIO_Pin = GPIO_Pin_5;
led.GPIO_Mode = GPIO_Mode_OUT;
led.GPIO_OType = GPIO_OType_PP;
led.GPIO_Speed = GPIO_Speed_2MHz;
led.GPIO_PuPd = GPIO_PuPd_NOPULL;
And now initialize the structure.
GPIO_Init(GPIOD, &led);
 b) User button

The blue user button is connected with PA0. Let's configure it in input pushpull mode with the pull-up.
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

GPIO_InitTypeDef b;
b.GPIO_Mode = GPIO_Mode_IN;
b.GPIO_Speed = GPIO_Speed_2MHz;
b.GPIO_OType = GPIO_OType_PP;
b.GPIO_PuPd = GPIO_PuPd_UP;

GPIO_Init(GPIOA, &b);
c) Main program

The simplest part. Check in loop whether the button was pressed and if so, toggle the LED. 
while (1) {
    if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0)) {
      GPIO_ToggleBits(GPIOD, GPIO_Pin_5);
      delay();
    }
  }
Note: The button is pretty sensitive on click so we added a delay to prevent the LED from blinking too much.


Leave a comment

Anonymous said...

Your full code is in the trash. Can't view it

Mary - Kate said...

I've updated the link, try again. :)