Skip to content

Instantly share code, notes, and snippets.

@jollyroger
Last active August 29, 2015 14:09
Show Gist options
  • Save jollyroger/4befe8f9b1fabb6c54c2 to your computer and use it in GitHub Desktop.
Save jollyroger/4befe8f9b1fabb6c54c2 to your computer and use it in GitHub Desktop.
/*
Door timer
Controls light in the room by door state:
* when door opens: turn light on until time less than DELAY_OPEN value
* when door closes: turn light off after time reaches DELAY_CLOSE value
Separately control timer for two rooms
Pins used:
* Digital 2-3 --- wait for interrupts from switches
* Digital 4-5 --- control relays
* Digital 8-12 --- select DELAY_OPEN value from array based on pin input
*/
#define SECOND 1000L // used to calulate delayss
#define MINUTE 60000L // used to calulate delayss
// Door button pins to control relays
#define DOOR_BUTTON_1 2
#define DOOR_BUTTON_2 3
// Relay pins
#define RELAY_1 4
#define RELAY_2 5
// Rotary switch pins
#define SWITCH_MIN 8
#define SWITCH_MAX 12
#define DELAY_TIME 1*SECOND // how frequent timer state is updated
#define NUM_PRESETS 5 // number of positions switch has
long presets[NUM_PRESETS] = {
5 * MINUTE,
10 * MINUTE,
15 * MINUTE,
30 * MINUTE,
60 * MINUTE
}; // preset values for TIMER_OPEN
long DELAY_CLOSE = 10 * SECOND; // wait this much before turning off the lights when the door is closed
long DELAY_OPEN = presets[0];
volatile boolean door1_open = false;
volatile long door1_time = 0;
volatile boolean door2_open = false;
volatile long door2_time = 0;
void setup() {
// Initialize switches
pinMode(DOOR_BUTTON_1, INPUT);
attachInterrupt(0, door1, CHANGE);
pinMode(DOOR_BUTTON_2, INPUT);
attachInterrupt(1, door2, CHANGE);
// Initialize relay control
pinMode(RELAY_1, OUTPUT);
pinMode(RELAY_2, OUTPUT);
// Initialize Switch pins
for(int pin = SWITCH_MIN; pin <= SWITCH_MAX; pin++) pinMode(pin, INPUT);
}
void loop() {
DELAY_OPEN = presets[read_preset()];
long door1_delay = door1_open ? DELAY_OPEN : DELAY_CLOSE;
if ( door1_time >= door1_delay) {
digitalWrite(RELAY_1, HIGH);
} else { door1_time += DELAY_TIME; }
long door2_delay = door2_open ? presets[read_preset()] : DELAY_CLOSE;
if ( door2_time >= door2_delay) {
digitalWrite(RELAY_2, HIGH);
} else {door2_time += DELAY_TIME; }
delay(DELAY_TIME);
}
long read_preset() {
int i;
int preset;
// read values from switch pins, defaulting to lowest value
for (i = SWITCH_MAX; i>=SWITCH_MIN; i--) {
preset = i - SWITCH_MIN;
if (digitalRead(i) == HIGH) break;
}
return preset;
}
void door1() {
door1_open = digitalRead(DOOR_BUTTON_1) == HIGH;
door1_time = 0;
if (door1_open == HIGH) {
digitalWrite(RELAY_1, LOW);
}
}
void door2() {
door2_open = digitalRead(DOOR_BUTTON_2) == HIGH;
door2_time = 0;
if (door2_open) {
digitalWrite(RELAY_2, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment