30th August 2017

ARM Blinking LED(s) library with callbacks

Why the LED driver?

I see many posts on the internet, the forum questions about the proper way of LED blinking. I have decided to write simple interrupt driven library to help hobbyists with this task.

Main features:

  • Any number of connected LEDs
  • All LEDs have configurable OFF and ON times
  • Configurable number of LED blinks
  • Callback function after the blink count (to change the pattern for example)
  • Configurable current sink or source configuration
  • Any timer callback can be used (i.e. you just need to call my callback function from your interrupt handler)

Time is measured in the timer callbacks. In the example below I use the SysTick which calls the callback function every 1ms (1000 times / sec). You can use any frequency but you have to remember to use the correct units. For example, if the timer used, invokes the LED callback function 50  times per second, your time unit is 1/50 sec. To have LED ON for 0.1 seconds and OFF for 0.3 sec 5 and respectivelly 15 units should be used. To offload the µController you can skip some of the callbacks (it is confugurable by the #define in the library)

Implemented functions:

int AddLED(GPIO_TypeDef *gpio, uint8_t pin, int type, void (*callback)(int));
Adds LED to the pool. It has to be first operation before any other operation


  • gpio – LED pin port
  • pin – pin number
  • typeSOURCE o SINK. SOURCE – LED is activated by high pin level. SINK – by low pin level
  • callback – function to be called after the set number of LED blinks. NULL – no callback

Returns: LED handler

void SetTimeLED(int led, uint16_t ontime, uint16_t offtime, uint16_t nblinks);
Sets LEDs timings.

  • led – LED handler returned by AddLED
  • ontime – time LED to be ON. 0 – permanently OFF, UINT16_MAX – permanently on
  • offtime – time LED to be OFF.
  • nblinks – number of blinks in this sequence. 0 – no limit. After nblinks LED is turned OFF and the callback function called

void ToggleLED(GPIO_TypeDef *gpio, int pin); // toggles the particular pin
void OnLED(int led);                         // works only when blinking is off
void OffLED(int led);                        // works only when blinking is off

The example below sets two LEDs, and initialises the sequence of blinking as described in the code comments

You can see this demo in action on the STM21F103 minimum development board form China ( the “Blue Pill”). 


Leave a Reply

Your email address will not be published. Required fields are marked *