-
Notifications
You must be signed in to change notification settings - Fork 0
/
wc.h
78 lines (65 loc) · 1.37 KB
/
wc.h
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
#pragma once
#include "utils.h"
/* Wall clock module */
#define WC_DIGITS 4
/* We are expecting 793.5 Hz update rate (26MHz / (4*8192)) */
#define WC_DIV 7935
/* We are measuring time in 1/100 sec units */
#define WC_DELTA 1000
struct wc_ctx {
unsigned char d[WC_DIGITS];
unsigned cnt;
unsigned volatile ticks;
};
static inline void wc_reset(struct wc_ctx* wc)
{
int i;
for (i = 0; i < WC_DIGITS; ++i)
wc->d[i] = 0;
wc->cnt = 0;
}
static inline int wc_tick(struct wc_ctx* wc)
{
int i;
wc->cnt += WC_DELTA;
if (wc->cnt < WC_DIV)
return 0;
wc->cnt -= WC_DIV;
for (i = 0; i < WC_DIGITS; ++i)
if (++wc->d[i] < 10)
return i + 1;
else
wc->d[i] = 0;
return WC_DIGITS + 1;
}
static inline int wc_update(struct wc_ctx* wc)
{
++wc->ticks;
return wc_tick(wc);
}
static inline int wc_advance(struct wc_ctx* wc, int ticks)
{
int r, res = 0;
for (; ticks; --ticks)
if ((r = wc_tick(wc)) > res)
res = r;
return res;
}
static inline unsigned wc_get_time(struct wc_ctx* wc)
{
return pack4nibbles(wc->d);
}
static inline void wc_set_time(struct wc_ctx* wc, unsigned time)
{
unpack4nibbles(time, wc->d);
}
static inline void wc_delay_(struct wc_ctx* wc, unsigned ticks, void (*cb)(void))
{
unsigned expired = wc->ticks + ticks;
while (wc->ticks != expired)
if (cb) cb();
}
static inline void wc_delay(struct wc_ctx* wc, unsigned ticks)
{
wc_delay_(wc, ticks, 0);
}