#define LOOP_DELAY 200 // MILLISECONDS - how much time we wait before check if a new command infrared are send by user #define TIMEOUT_DELAY 500 // MILLISECONDS - i'm guessing here, this needs to be longer than the IR repeat intervalsend#define INITIALIZATION_DELAY 4000 // MILLISECONDS - time to wait before end of initialization

int relayOn = null; // we store active relay pin when user press button for put on/offunsigned long lastButtonTime = millis(); // we store time when we see last time user press button, so we can know how much time since user release buttonunsigned long actualButtonTime; // we store atual time - lastButtonTime for check if time are out and we need stop relay on

delay(INITIALIZATION_DELAY); // check that all relays are inactive at Reset DEBUG_PRINTLN("End initialization");}

void loop(){ if (irReceiver.decode(&irResults)) // if we have a code receveid { // we check if code received are a correct command switch (irResults.value) { case TC_BED_UP: // user press button for make up the bed relayOpen(PIN_RELAY_BED_UP); break; case TC_BED_DOWN: // user press button for make down the bed relayOpen(PIN_RELAY_BED_DOWN); break; case TC_BUST_UP: // user press button for make up the bed bust relayOpen(PIN_RELAY_BUST_UP); break; case TC_BUST_DOWN: // user press button for make down the bed bust relayOpen(PIN_RELAY_BUST_DOWN); break; case REPEAT: // user continue press a button if (relayOn != null) // if we have a relay already on it's a correct button user stay on { lastButtonTime = millis(); // update the time-out } break; }

irReceiver.resume(); // receive the next value }

// if a relay are on // and millis() reset to 0 automatically when overflow, so if less than lastButtonTime we stop for prevent bug // or turn off relay if time is out, user stop push button actualButtonTime = millis(); // actual time since arduino start if (relayOn != null && (actualButtonTime < lastButtonTime || (actualButtonTime - lastButtonTime) > TIMEOUT_DELAY)) { relayClose(); }

delay(LOOP_DELAY);}

void relayOpen(int relay){ relayClose(); // if a relay are on we stop it before set another on, bed cannot going up and down at same time...

relayOn = relay; // we save witch relay are now on digitalWrite(relayOn, RELAY_ON); // we set relay on lastButtonTime = millis(); // we keep time for check time out relayStatePrint("on"); //we print witch relay are on}

void relayClose(){ // we check if a relay are on else nothing to do if (relayOn != null) { digitalWrite(relayOn, RELAY_OFF); // we set to off relay actually on relayStatePrint("off"); // we print witch relay are off before reset var because relayOn are used in function relayStatePrint relayOn = null; // no more relay are on }}