]> mj.ucw.cz Git - home-hw.git/blob - lib/util.h
BSB: An attempt at sending
[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
28 #define UNUSED __attribute__((unused))
29
30 // Unaligned access to data
31
32 static inline uint get_u16_le(byte *p)
33 {
34         return (p[1] << 8) | p[0];
35 }
36
37 static inline uint get_u16_be(byte *p)
38 {
39         return (p[0] << 8) | p[1];
40 }
41
42 static inline uint get_u32_le(byte *p)
43 {
44         return (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
45 }
46
47 static inline uint get_u32_be(byte *p)
48 {
49         return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
50 }
51
52 static inline void put_u16_le(byte *p, u16 x)
53 {
54         p[0] = x;
55         p[1] = x >> 8;
56 }
57
58 static inline void put_u16_be(byte *p, u16 x)
59 {
60         p[0] = x >> 8;
61         p[1] = x;
62 }
63
64 static inline void put_u32_be(byte *p, u32 x)
65 {
66         p[0] = x >> 24;
67         p[1] = (x >> 16) & 0xff;
68         p[2] = (x >> 8) & 0xff;
69         p[3] = x & 0xff;
70 }
71
72 static inline void put_u32_le(byte *p, u32 x)
73 {
74         p[3] = x >> 24;
75         p[2] = (x >> 16) & 0xff;
76         p[1] = (x >> 8) & 0xff;
77         p[0] = x & 0xff;
78 }
79
80 // CPU instructions not covered by libopencm3
81
82 static inline void wait_for_interrupt(void)
83 {
84         asm volatile ("wfi");
85 }
86
87 // util-debug.c
88
89 void debug_printf(const char *fmt, ...) __attribute__((format(printf,1,2)));
90 void debug_puts(const char *s);
91 void debug_putc(int c);
92
93 void debug_led(bool light);
94 void debug_led_toggle(void);