Advertisement
macca-nz

Delay_Relay_ON_Servo_Open_ONLY

Jan 19th, 2021
85
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Servo.h>
  2. const int DC = 2;
  3. const int TS = A0;
  4. const int TSpin = 3;
  5. #define srclosed 0                          //Define Servo Open position
  6. #define sropen 180                          //Define Servo Closed position
  7. byte TSpos;                                 //Variable to hold servo position
  8. unsigned long wait = 2000;                  //Delay a to let servo reach OPEN position before switching ON relay
  9. unsigned long waitTime = 0;            
  10. unsigned long debounceDelay = 50;           //debounce delay so you don't get a false positve with a contact bounce
  11. unsigned long debounceTime = 0;
  12. boolean runOnce = true;                     //This creates a run once for the delay
  13. Servo tsServo;
  14.  
  15. void setup(){
  16.   pinMode(TS, INPUT);
  17.   pinMode(DC, OUTPUT);
  18.   digitalWrite(DC, LOW);                    //Sets startup state for relay
  19.   tsServo.attach(TSpin);
  20.   TSpos = srclosed;                         //Sets startup state for servo
  21.   tsServo.write(TSpos);
  22. }
  23.  
  24. void loop(){
  25.  
  26.   int DCstate = digitalRead(DC);
  27.   int TSstate = digitalRead(TS);
  28.  
  29.   if (TSstate == 1){
  30.     if(millis() - debounceTime > debounceDelay){
  31.       debounceTime = millis();
  32.         if(TSpos == srclosed){
  33.           waitTime = millis();
  34.           TSpos = sropen;
  35.           runOnce = false;
  36.         }else{
  37.           DCstate = LOW;
  38.           TSpos = srclosed;
  39.         }
  40.       }
  41.     }  
  42.    
  43.   if(runOnce == false){
  44.     if((millis() - waitTime) > wait){
  45.     DCstate = HIGH;
  46.     runOnce = true;
  47.     waitTime = millis();
  48.     }
  49.   }
  50.   digitalWrite(DC, DCstate);
  51.   tsServo.write(TSpos);
  52. }
Advertisement
RAW Paste Data Copied
Advertisement