busy_wait.h
1 /*
2  * Copyright (C) 2024 ML!PA Consulting GmbH
3  *
4  * This file is subject to the terms and conditions of the GNU Lesser
5  * General Public License v2.1. See the file LICENSE in the top level
6  * directory for more details.
7  */
8 
21 #ifndef BUSY_WAIT_H
22 #define BUSY_WAIT_H
23 
24 #include <stdint.h>
25 #include "periph_conf.h"
26 #include "time_units.h"
27 
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31 
38 #ifndef CPU_CYCLES_PER_LOOP
39 #define CPU_CYCLES_PER_LOOP 3
40 #endif
41 
50 static inline void busy_wait(unsigned loops)
51 {
52  while (loops) {
53  /* This empty inline assembly should be enough to convince the
54  * compiler that the loop cannot be optimized out. Tested with
55  * GCC 12.2 and clang 16.0.0 successfully. */
56  __asm__ __volatile__ (
57  ""
58  : /* no outputs */
59  : /* no inputs */
60  : /* no clobbers */
61  );
62  loops--;
63  }
64 }
65 
77 static inline void busy_wait_us(unsigned usec)
78 {
79  unsigned loops = ((uint64_t)usec * CLOCK_CORECLOCK)
81  busy_wait(loops);
82 }
83 
84 #ifdef __cplusplus
85 }
86 #endif
87 
88 #endif /* BUSY_WAIT_H */
#define CLOCK_CORECLOCK
Clock configuration.
Definition: periph_cpu.h:31
static void busy_wait_us(unsigned usec)
Spin for a number of microseconds.
Definition: busy_wait.h:77
static void busy_wait(unsigned loops)
Spin for a number of cycles.
Definition: busy_wait.h:50
#define CPU_CYCLES_PER_LOOP
CPU cycles per busy wait loop iteration.
Definition: busy_wait.h:39
#define US_PER_SEC
The number of microseconds per second.
Definition: time_units.h:85
Utility header providing time unit defines.