Hi,
This code works, however if I press the on/off switch that triggers the interrupt quickly, I can end up with the final status being sent incorrect. Any advice re how to avoid double-bounce here, or more correctly how to ensure that the last message that goes out does truely reflect correct start of button (i.e. on or off)...
#include <WString.h>
#include <VirtualWire.h>
#include <avr/sleep.h>
#define REED_SWITCH 2
#define REED_SWITCH_INTERRUPT 0
#define LED 13
#define RF_POWER_PIN 3
void setup()
{
// Debugging
Serial.begin(9600); // Debugging only
// Pin Modes
pinMode(REED_SWITCH, INPUT);
pinMode(LED, OUTPUT);
pinMode(RF_POWER_PIN, OUTPUT);
// VirtualWire Setup
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2000); // Bits per sec
}
void updateBase() {
digitalWrite(RF_POWER_PIN, true);
int val = digitalRead(REED_SWITCH);
String door_status;
if (val == HIGH) {
door_status = "OPEN";
} else {
door_status = "CLOSED";
}
String msgPre = "The door is now: ";
msgPre.append(door_status);
char *msg = door_status.getChars();
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(RF_POWER_PIN, false);
}
void loop()
{
sleepNow();
delay (10);
updateBase();
}
void wakeUpNow() // here the interrupt is handled after wakeup
{
}
void sleepNow() // here we put the arduino to sleep
{
Serial.println("sleepNow");
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable(); // enables the sleep bit in the mcucr register
// so sleep is possible. just a safety pin
setupInterrupt();
sleep_mode(); // here the device is actually put to sleep!!
// THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
sleep_disable(); // first thing after waking from sleep:
// disable sleep...
detachInterrupt(REED_SWITCH_INTERRUPT); // disables interrupt 0 on pin 2 so the
// wakeUpNow code will not be executed
// during normal running time.
}
void setupInterrupt() {
attachInterrupt(REED_SWITCH_INTERRUPT ,wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
// wakeUpNow when pin 2 gets LOW
}