aboutsummaryrefslogtreecommitdiffstats
path: root/src/hal/components/toggle.comp
blob: 96eda58059a7b59ee1bd3c45ce28ee92769290c3 (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
component toggle "'push-on, push-off' from momentary pushbuttons";

description
"""
     ┐     ┏──┐        ┏──┐  
.br
in : └─────┛  └────────┛  └──
.br
     ┐     ┌───────────┐     
.br
out: └─────┘           └─────
""";

pin in bit in "button input";
pin io bit out "on/off output";
param rw u32 debounce = 2 "debounce delay in periods";
option data toggle_data;

function _ nofp;
license "GPL";
author "John Kasunich";
;;

typedef struct {
    int debounce_cntr;
    int debounced;
} toggle_data;

FUNCTION(_) {

    if (( debounce < 1 ) || ( debounce > 10000 )) {
	/* set a sane value, we don't want 2 million second delays */
	debounce = 2;
    }
    if ( in ) {
	/* pressed */
	data.debounce_cntr++;
	if ( data.debounce_cntr >= debounce ) {
	    data.debounce_cntr = debounce;
	    if ( data.debounced == 0 ) {
		/* toggle output */
		out = !out;
	    }
	    data.debounced = 1;
	}
    } else {
	/* not pressed */
	data.debounce_cntr--;
	if ( data.debounce_cntr <= 0 ) {
	    data.debounce_cntr = 0;
	    data.debounced = 0;
	}
    }
}
bues.ch cgit interface