summaryrefslogtreecommitdiffstats
path: root/myavr_mk2/util.h
blob: 7007dde50c1b7c6dc67f8c9ecaca0522bfdbb79a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifndef MY_UTIL_H_
#define MY_UTIL_H_

#ifndef F_CPU
# warning "F_CPU not defined"
# define F_CPU	3686400
#endif
#include <util/delay.h>

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/cpufunc.h>


#define min(a, b)	({			\
		__typeof__(a) __a = (a);	\
		__typeof__(b) __b = (b);	\
		__a < __b ? __a : __b;		\
	})

#define max(a, b)	({			\
		__typeof__(a) __a = (a);	\
		__typeof__(b) __b = (b);	\
		__a > __b ? __a : __b;		\
	})

#define clamp(value, min_val, max_val)		\
	max(min(value, max_val), min_val)

#define abs(val)	({			\
		__typeof__(val) __val = (val);	\
		__val >= 0 ? __val : -__val;	\
	})

#define ARRAY_SIZE(x)		(sizeof(x) / sizeof((x)[0]))

/* Progmem pointer annotation. */
#define PROGPTR			/* progmem pointer */

#define mb()			__asm__ __volatile__("" : : : "memory")


#define noinline        __attribute__((__noinline__))
#define _packed		__attribute__((__packed__))


typedef _Bool		bool;


static inline void irq_disable(void)
{
	cli();
	mb();
}

static inline void irq_enable(void)
{
	mb();
	sei();
}

static inline uint8_t irq_disable_save(void)
{
	uint8_t sreg = SREG;
	cli();
	mb();
	return sreg;
}

static inline void irq_restore(uint8_t sreg_flags)
{
	mb();
	SREG = sreg_flags;
}

static inline bool __irqs_enabled(uint8_t sreg_flags)
{
	return !!(sreg_flags & (1 << SREG_I));
}

static inline bool irqs_enabled(void)
{
	return __irqs_enabled(SREG);
}

#endif /* MY_UTIL_H_ */
bues.ch cgit interface