Blink LEDs like a pro

The talk's presentation can be found here. On the 14th of October 2019 Rafael has shown us how to make LEDs blink on with a microcontroller - not quite, because this can be done in various differnt ways.

He showed us five ways to blink a LED. The first one is quiet easy and there's no code required - really - just a connection between the microcontroller and a debugger, where one can change the control value of the LED by hand, making it blink.

Another way is to write an infinite loop which switches the LED on, then the program waits some time, afterwards it switches it off, then waits again and returns to the the beginning. By the way, the program execution is stalled by simple executing a long for loop. Note: GPIOC_MODER is a virtual pointer to the LED control value.

/* Crude delay function */
void delay(uint32_t count) {
    for (int i = 0; i < count; i++) {
        __asm__("nop");
    }
}

int main() {
    /* Initialize APB2 (Advanced Peripheral Bus 2) */
    *RCC_APB2ENR = 0x10;
    /* Set GPIO port C pin 13 as output */
    *GPIOC_MODER |= 0x200000;

    /* Set and Reset Output Data Register of PC13 */
    while (1) {
        *GPIOC_ODR = 0x2000;
        delay(200000);
        *GPIOC_ODR = 0x0;
        delay(200000);
    }
}

This doesn't look like good C, because it is really low level. The presenter introduced as the HAL (Hardware abstraction layer), so our C program has the ability to look better. The next program's main function simply consists of an empty infinite loop which does nothing, preventing the program from terminating. Before that, a timer is created which periodically triggers an interupt. It toggles our LED control value or - in other words - making it blink.

But this solution still uses the CPU of our microcontroller. This time another empty infinity loop is used. Just before that the direct memory access controller, or short DMA, is instructed to write an array of zeros and ones periodically to the LED's control value. So the LED blinks again.

Just now last program still used basic microcontroller instructions. We could just install RTOS (Real-time operatoring system) and write a typical software program to make the LED blink yet again.