blob: 02e72fb3832b7d3a85ebf0fe17a068a664d03e77 [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 Silverman25a06d92013-12-15 16:28:52 -080016// Count leading zeros.
17// Returns 0 if bit 31 is set etc.
18__attribute__((always_inline)) static __INLINE uint32_t __clz(uint32_t value) {
19 uint32_t result;
20 __asm__("clz %0, %1" : "=r" (result) : "r" (value));
21 return result;
22}
23
Brian Silverman1b6fbd02013-12-12 18:08:47 -080024// Sets number_of_bits (shifted left shift number of slots) to value in
25// variable.
26// This means that the total shift is number_bits*shift.
27#define SET_BITS(variable, number_bits, value, shift) do { \
28 variable = (((variable) & \
29 ~(((1 << (number_bits)) - 1) << (shift * (number_bits)))) | \
30 ((value) << (shift * (number_bits)))); \
31} while (0);
32
33// A convenient way to set up a GPIO pin for some alternate function without
34// missing part or messing up which bits need setting to what.
35// pin is the 0-indexed pin number.
36// afr is 0-0xF for the various alternate functions.
37static inline void gpio_setup_alt(GPIO_TypeDef *port, int pin, int afr) {
38 SET_BITS(port->MODER, 2, 2 /* alternate function */, pin);
39 if (pin < 8) {
40 SET_BITS(port->AFR[0], 4, afr, pin);
41 } else {
42 SET_BITS(port->AFR[1], 4, afr, (pin - 8));
43 }
44}
45
Brian Silverman18b01642013-12-13 21:12:25 -080046// A convenient way to set up a GPIO pin for output (push-pull) without missing
47// part or messing up which bits need setting to what.
48// speed is 0 (slow) to 3 (fast)
49static inline void gpio_setup_out(GPIO_TypeDef *port, int pin, int speed) {
50 SET_BITS(port->MODER, 2, 1 /* output */, pin);
51 SET_BITS(port->OSPEEDR, 2, speed, pin);
52}
53
Brian Silverman25a06d92013-12-15 16:28:52 -080054// exti is which EXTI line to set
55// port is 0 for A, 1 for B, etc
56static inline void EXTI_set(int exti, int port) {
57 SET_BITS(SYSCFG->EXTICR[exti / 4], 4, port, exti % 4);
58}
59
Brian Silvermanaa9183a2013-12-08 10:33:47 -080060#endif // CAPE_UTIL_H_