]> mj.ucw.cz Git - home-hw.git/blob - lib/util.h
Rolety: Annotation
[home-hw.git] / lib / util.h
1 /*
2  *      General Utility Library for STM32
3  *
4  *      (c) 2018--2019 Martin Mareš <mj@ucw.cz>
5  */
6
7 #include <stdbool.h>
8 #include <stddef.h>
9 #include <stdint.h>
10
11 #include "config.h"
12
13 // Types
14
15 typedef unsigned int uint;
16 typedef uint8_t byte;
17 typedef uint16_t u16;
18 typedef int16_t s16;
19 typedef uint32_t u32;
20 typedef int32_t s32;
21
22 // Macros
23
24 #define MIN(x,y) ((x) < (y) ? (x) : (y))
25 #define MAX(x,y) ((x) > (y) ? (x) : (y))
26 #define CLAMP(x,min,max) ({ typeof(x) _t=x; (_t < min) ? min : (_t > max) ? max : _t; })
27 #define ARRAY_SIZE(ary) (sizeof(ary)/sizeof((ary)[0]))
28
29 #define UNUSED __attribute__((unused))
30
31 // Unaligned access to data
32
33 static inline uint get_u16_le(byte *p)
34 {
35         return (p[1] << 8) | p[0];
36 }
37
38 static inline uint get_u16_be(byte *p)
39 {
40         return (p[0] << 8) | p[1];
41 }
42
43 static inline uint get_u32_le(byte *p)
44 {
45         return (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
46 }
47
48 static inline uint get_u32_be(byte *p)
49 {
50         return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
51 }
52
53 static inline void put_u16_le(byte *p, u16 x)
54 {
55         p[0] = x;
56         p[1] = x >> 8;
57 }
58
59 static inline void put_u16_be(byte *p, u16 x)
60 {
61         p[0] = x >> 8;
62         p[1] = x;
63 }
64
65 static inline void put_u32_be(byte *p, u32 x)
66 {
67         p[0] = x >> 24;
68         p[1] = (x >> 16) & 0xff;
69         p[2] = (x >> 8) & 0xff;
70         p[3] = x & 0xff;
71 }
72
73 static inline void put_u32_le(byte *p, u32 x)
74 {
75         p[3] = x >> 24;
76         p[2] = (x >> 16) & 0xff;
77         p[1] = (x >> 8) & 0xff;
78         p[0] = x & 0xff;
79 }
80
81 // CPU instructions not covered by libopencm3
82
83 static inline void wait_for_interrupt(void)
84 {
85         asm volatile ("wfi");
86 }
87
88 // A compiler memory barrier
89
90 static inline void barrier(void)
91 {
92         asm volatile ("" : : : "memory");
93 }
94
95 // util-debug.c
96
97 void debug_printf(const char *fmt, ...) __attribute__((format(printf,1,2)));
98 void debug_puts(const char *s);
99 void debug_putc(int c);
100 void debug_flush(void);
101
102 void debug_led(bool light);
103 void debug_led_toggle(void);