From 4e72a3da3e15a6ee5cbdf834fa985630dbd5ef9a Mon Sep 17 00:00:00 2001 From: Nicolae Hodos Date: Tue, 22 Nov 2016 00:48:26 +0100 Subject: [PATCH] short press-on, long press-off --- lamp_switch/lamp_switch.ino | 98 ++++++++++++++++++++++++++++++++----- 1 file changed, 86 insertions(+), 12 deletions(-) diff --git a/lamp_switch/lamp_switch.ino b/lamp_switch/lamp_switch.ino index 374f241..2fb08cf 100644 --- a/lamp_switch/lamp_switch.ino +++ b/lamp_switch/lamp_switch.ino @@ -1,8 +1,18 @@ -#include #include #include #include +#define DEBUG 0 +#define RC_SWITCH 1 + +#if RC_SWITCH +#include +#endif + +#if DEBUG +#include +#endif + // Utility macros #define adc_disable() (ADCSRA &= ~_BV(ADEN)) // disable ADC (before power-off) #define adc_enable() (ADCSRA |= _BV(ADEN)) // re-enable ADC @@ -10,38 +20,82 @@ // Pins #define SWITCH 0 + +#if DEBUG +#define RxD 0 +#define TxD 1 +SoftwareSerial AttinySerial(RxD,TxD); +#endif + +#if RC_SWITCH #define SENDER 2 - RCSwitch mySwitch = RCSwitch(); +#endif +void sleep(); +void enableWdt(); +void disableWdt(); +void debug(const char* msg); + +char* group = "11111"; +int number = 4; bool stateOn = false; +bool timerTriggered = false; void setup() { +#if DEBUG + AttinySerial.begin(9600); +#endif + +#if RC_SWITCH pinMode(SWITCH, INPUT_PULLUP); - mySwitch.enableTransmit(SENDER); mySwitch.setProtocol(1); +#endif set_sleep_mode(SLEEP_MODE_PWR_DOWN); enable_pin_interrupts(); - } void loop() { sleep(); } -void sendCommand() { +void sendCommand(boolean on) { + if (on) { +#if RC_SWITCH + mySwitch.switchOn((char*)"11111", 4); +#endif + debug("switch on"); + } else { +#if RC_SWITCH + mySwitch.switchOff((char*)"11111", 4); +#endif + debug("switch off"); + } +} + +ISR(PCINT0_vect) { byte state = digitalRead(SWITCH); if (state == LOW) { - if (stateOn) { - mySwitch.switchOff((char*)"11111", 4); - } else { - mySwitch.switchOn((char*)"11111", 4); + debug("state is low"); + enableWdt(); + } else { + debug("state is high"); + disableWdt(); + if (!timerTriggered) { + sendCommand(true); } - stateOn = !stateOn; } + timerTriggered = false; +} + +ISR(WDT_vect) { + debug("wdt"); + sendCommand(false); + timerTriggered = true; + disableWdt(); } void sleep() { @@ -61,7 +115,27 @@ void sleep() { sei(); // Enable interrupts } -ISR(PCINT0_vect) { - sendCommand(); +//enable the wdt for 1 sec interrupt +void enableWdt() { + cli(); + MCUSR = 0x00; + WDTCR |= _BV(WDCE) | _BV(WDE); + WDTCR = _BV(WDIE) | _BV(WDP2) | _BV(WDP1); + sei(); +} + +void disableWdt() { + cli(); + wdt_reset(); + MCUSR = 0x00; + WDTCR |= _BV(WDCE) | _BV(WDE); + WDTCR = 0x00; + sei(); +} + +void debug(const char* msg) { +#if DEBUG + AttinySerial.println(msg); +#endif }