</>EmbeddedInterview

Implement a delay without using a library function.

Easy"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>

/* Cortex-M3/M4/M7: cycle-accurate busy wait using the DWT cycle counter */
#define DEMCR      (*(volatile uint32_t *)0xE000EDFCu)
#define DWT_CTRL   (*(volatile uint32_t *)0xE0001000u)
#define DWT_CYCCNT (*(volatile uint32_t *)0xE0001004u)

extern uint32_t SystemCoreClock;                 /* Hz, set by the clock setup code */

void dwt_init(void)
{
    DEMCR |= (1u << 24);                         /* TRCENA: enable DWT */
    DWT_CYCCNT = 0;
    DWT_CTRL |= 1u;                              /* CYCCNTENA */
}

void delay_us(uint32_t us)
{
    uint32_t start = DWT_CYCCNT;
    uint32_t ticks = us * (SystemCoreClock / 1000000u);
    while ((uint32_t)(DWT_CYCCNT - start) < ticks) { }   /* wrap-safe */
}

/* millisecond delay from a 1 ms SysTick counter */
extern volatile uint32_t g_ms;
void delay_ms(uint32_t ms) { uint32_t s = g_ms; while ((uint32_t)(g_ms - s) < ms) { } }

Points: a plain for (i = 0; i < N; i++); loop is a bad delay: the optimiser can delete it, and its duration changes with clock speed, flash wait states and compiler flags (add volatile and calibrate if you must). Hardware counters give accurate timing; unsigned subtraction handles wrap-around. Busy delays waste CPU and power: use timers or an RTOS delay for anything long. (Cortex-M0/M0+ has no DWT counter: use SysTick or a timer.)