summaryrefslogtreecommitdiffstats
path: root/firmware/onoffswitch.c
blob: fc0428d56a363d09ead6450dd4f04cf3213f2dfb (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
88
89
90
91
92
93
94
95
96
/*
 * On/off-switch
 *
 * Copyright (c) 2014 Michael Buesch <m@bues.ch>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "onoffswitch.h"
#include "util.h"
#include "main.h"

#include <avr/io.h>


/* Port definitions for the hardware on/off-switch. */
#define ONOFFSWITCH_DDR			DDRD
#define ONOFFSWITCH_PORT		PORTD
#define ONOFFSWITCH_PIN			PIND
#define ONOFFSWITCH_BIT			PD3

/* Saved state. */
static enum onoff_state onoffswitch_state = ONOFF_IS_OFF;
/* Timestamp for the next check. */
static jiffies_t next_check;


static void onoffswitch_eliminate_edge_states(void)
{
	if (onoffswitch_state == ONOFF_SWITCHED_ON)
		onoffswitch_state = ONOFF_IS_ON;
	else if (onoffswitch_state == ONOFF_SWITCHED_OFF)
		onoffswitch_state = ONOFF_IS_OFF;
}

static void onoffswitch_update(void)
{
	bool new_state, old_state;

	/* Get the state. */
	new_state = !!(ONOFFSWITCH_PIN & (1 << ONOFFSWITCH_BIT));
	/* Switch logic is inverted. */
	new_state = !new_state;

	/* Detect state and edges. */
	old_state = (onoffswitch_state != ONOFF_IS_OFF);
	if (new_state && !old_state)
		onoffswitch_state = ONOFF_SWITCHED_ON;
	else if (!new_state && old_state)
		onoffswitch_state = ONOFF_SWITCHED_OFF;
	else if (new_state)
		onoffswitch_state = ONOFF_IS_ON;
	else
		onoffswitch_state = ONOFF_IS_OFF;
}

/* Initialize the on/off-switch. */
void onoffswitch_init(void)
{
	ONOFFSWITCH_DDR &= ~(1 << ONOFFSWITCH_BIT);
	ONOFFSWITCH_PORT |= (1 << ONOFFSWITCH_BIT);
	_delay_ms(20); /* Wait for pull-up. */
	onoffswitch_update();
	onoffswitch_eliminate_edge_states();
}

/* Periodic work. */
void onoffswitch_work(void)
{
	jiffies_t now = jiffies_get();

	onoffswitch_eliminate_edge_states();

	if (!time_before(now, next_check)) {
		next_check = now + msec_to_jiffies(100);
		onoffswitch_update();
	}
}

/* Get the on/off-switch state. */
enum onoff_state onoffswitch_get_state(void)
{
	return onoffswitch_state;
}
bues.ch cgit interface