How to Create a Blinking LED Circuit with an STM32F407G Discovery Board in C

STM32F407G discovery board



In this article, we go over how to create a blinking LED circuit with an STM32F407G discovery board in C.

Previously, we showed how to turn on an LED, including the user LEDs included on the board or a custom LED that you connect to the board.

Now we will show how to make the LED turn on and off repeatedly, or blink or flash.

This is done by introducing a delay. You turn a device on, place in a delay, turn off the device, and place in another delay. You put in in a forever loop so that it blinks continuously.

The delay can be purely from software or it can be a combination of software and hardware (the on-board hardware timers).

As long as you understand how to turn on an LED, it's simply about how to add a delay in between the device being on and the device being off.

If you want to know how to turn on a digital device such as an LED, visit the article link show above.

In this article, we simply go over how to make the LED blink.

Using a purely software approach, the code to make the LED blink on and off is shown below.





We now will explain the code.

Within our main function, we declare 3 32-bit variables in order to be able to enable the peripheral clock, set PORTD pin 12 as output, and write a digital HIGH to PORTD pin 12. This is all part of the standard process of turning on an LED.

We then enable the peripheral clock through the line, *pClkCtrlReg |= (1 << 3);

We set pin 12 as output through the line, *pPortDModeReg |= (1 << 24);

We then have our while loop.

This is a while(1) loop, so it runs forever. This is a loop that is always true, so it never ends.

We then turn on the LED using the line, *pPortDOutReg |= (1 << 12);

This writes a 1 or a HIGH signal to pin 12, turning on the LED.

We then create a delay using a for loop that gives just about 1 second. So with the LED on, it keeps it on for just about 1 second.

We then turn the LED off using the line, *pPortDOutReg &= ~(1 << 12);

We then give the same second delay using the same for loop. This keeps the LED off for just about a second.

Since this code is within an infinite loop, it will then run over from the top again, turning on the LED, then turning it off, ...

So this is the purely software approach to introducing a time delay into code to be able to control how long an LED turns on for and how long it shuts off for.

If you need a longer delay, you simply extend the cycles in the for loop. If you need a shorter delay, you decrease the cycles in the for loop.

And this is how to create a blinking LED circuit with a STM32F407G discovery board in C.

Related Resources

How to Set Bits of a Number in C

How to Clear Bits of a Number in C



HTML Comment Box is loading comments...