blob: 893c95b8705d98cff83a1e572e5585f67483837c [file] [log] [blame]
Brian Silvermanaa9183a2013-12-08 10:33:47 -08001#ifndef CAPE_UTIL_H_
2#define CAPE_UTIL_H_
3
Brian Silverman1b6fbd02013-12-12 18:08:47 -08004#include <STM32F2XX.h>
5
Brian Silvermanaa9183a2013-12-08 10:33:47 -08006#define ALIAS_WEAK(f) __attribute__ ((weak, alias (#f)))
7
Brian Silverman2df84412013-12-10 14:00:40 -08008// MSG has to be separated_with_spaces.
9#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]
10
Brian Silvermanaa9183a2013-12-08 10:33:47 -080011// Prevents the compiler from reordering memory operations around this.
12static inline void compiler_memory_barrier(void) {
13 __asm__ __volatile__("" ::: "memory");
14}
15
Brian Silverman1b6fbd02013-12-12 18:08:47 -080016// Sets number_of_bits (shifted left shift number of slots) to value in
17// variable.
18// This means that the total shift is number_bits*shift.
19#define SET_BITS(variable, number_bits, value, shift) do { \
20 variable = (((variable) & \
21 ~(((1 << (number_bits)) - 1) << (shift * (number_bits)))) | \
22 ((value) << (shift * (number_bits)))); \
23} while (0);
24
25// A convenient way to set up a GPIO pin for some alternate function without
26// missing part or messing up which bits need setting to what.
27// pin is the 0-indexed pin number.
28// afr is 0-0xF for the various alternate functions.
29static inline void gpio_setup_alt(GPIO_TypeDef *port, int pin, int afr) {
30 SET_BITS(port->MODER, 2, 2 /* alternate function */, pin);
31 if (pin < 8) {
32 SET_BITS(port->AFR[0], 4, afr, pin);
33 } else {
34 SET_BITS(port->AFR[1], 4, afr, (pin - 8));
35 }
36}
37
Brian Silverman18b01642013-12-13 21:12:25 -080038// A convenient way to set up a GPIO pin for output (push-pull) without missing
39// part or messing up which bits need setting to what.
40// speed is 0 (slow) to 3 (fast)
41static inline void gpio_setup_out(GPIO_TypeDef *port, int pin, int speed) {
42 SET_BITS(port->MODER, 2, 1 /* output */, pin);
43 SET_BITS(port->OSPEEDR, 2, speed, pin);
44}
45
Brian Silvermanaa9183a2013-12-08 10:33:47 -080046#endif // CAPE_UTIL_H_