Skip to main content

Subsection 1.4.2 Part 2: A Better Delay, delay_ms()

The busy-wait loop produces an imprecise delay whose duration depends on the compiler optimization level and clock speed. We wrote a delay_ms() function for this course, which takes the number of milliseconds you want to wait as an argument; its code is in sysinit.c, in your mylib folder. From today on, use it instead of a delay loop. Replace the include line at the top of your source file:
// Day 1:
#include "stm32c0xx.h"

// Day 2 onward - use this instead:
#include "ES28.h"   // includes stm32c0xx.h AND the prototype for delay_ms()
With that change you can write readable, self-documenting delays:
#include "ES28.h"

#define GPIOAEN  (1U << 0)
#define LED_PIN  (1U << 5)

int main(void) {
    RCC->IOPENR  |= GPIOAEN;
    GPIOA->MODER |= (1U << 10);
    GPIOA->MODER &= ~(1U << 11);

    while (1) {
        GPIOA->ODR |= LED_PIN;   // LED on
        delay_ms(1000);           // wait 1 second

        GPIOA->ODR &= ~LED_PIN;  // LED off
        delay_ms(500);            // wait 0.5 second
    }
    return 0;
}