Controlling an LED via a GPIO pin on the STM32F4 Discovery board

Using GPIO to control an external LED

After getting an embedded LED blinking on the STM32F4 Discovery board the natural next step is to see if we can get a LED blinking on an external circuit!
Turns out, its not too hard!


This tutorial assumes you have a working development environment setup – if you haven’t got that far then refer to the first guide setting ‘Hello World – Blinking LED’ it will walk you through setting up all the tools you’ll need to build this project.

In order to get this example up and running you will require:

  • STM32F4 Discovery board and USB cable
  • A breadboard
  • A standard LED
  • A resistor approx 1k
  • Some wires or jumpers to connect the STM32F4 to the breadboard
Controlling an LED via a GPIO pin on the STM32F4 Discovery board

Controlling an LED via a GPIO pin on the STM32F4 Discovery board

For this project the STM32F4 board is going to supply the power to the LED, the circuit itself is extremely simple, it’s just one LED and a resistor in series connected to the GND pin and the PD5 port of the STM32F4 board. The code itself is almost exactly the same as the code for making the on board LED’s flash, in fact ive left that code in the project and as you can see in the video the on board LED’s are actually flashing away themselves.
The full code listing is at the bottom of the page, but ill break it down in steps to try and explain.

The first step is to initialise whats called the GPIOD clock, this is done with:


Once thats done the pins themselves are configured. Notice how the first line names the pins we are setting up, the pins GPIO_Pin_12,GPIO_Pin_13,GPIO_Pin_14,GPIO_Pin_15 represent the on board LED’s – and aren’t needed in this sample if you only want the external LED to flash. The GPIO_Pin_5 is the actual external pin on the STM32F4 Discovery board and is labelled PD5 on the board itself, this is the pin used to make the LED flash.

Once everything is configured the program enters the main loop and essentially takes it in turns to switch a pin on, then wait a set delay, switch the next pin on wait again ect until all the pins are on. Once there all on it waits a set delay again before switching all the pins to off then waiting a set delay before restarting the process.

This line turns the external LED on

This line turns all of the pins to off

If you didnt have this line you would find all the LEDs and PD5 would turn on and just stay on continuously.

See the video on you tube.

This sample is extremely simple, but it shows you the basics of controlling an external GPIO pin – have fun!! and look out for my next post where I will be showing you how to control the brightness of an external LED using pulse width modulation.


The complete code listing of the main.c file – if anyone would like the full project leave a reply and ill post it.

What are your thoughts?