Arduino Relay timer need help

A push button and led should have been added with this sketch. When the button is pressed once the led should turn on and off for a certain period of time
please help

AjitVk

#define relayPin 8 // the pin relay is connected
#define potPin  A0 // the pin potentiometer is connected
#define resetPin 3 // the pin where rest switch is connected
#define startPin 2 // the pin where start switch is connected

#define relayType 'L' // Relay trigger type. L for low and H for high

//because the time below is in millisecond, 1000ms=1 second, 1000x60=60000 is 1 minuets. 60x60x1000=3600000 is 1 hour
const long maxTime = 30000;// maximum timer time in milliseconds. for one minute =60000, 1 hours =3600000
const long minTime = 3000; // miniimum timer time in milliseconds

// do not change anything bellow here
long duration;
int potValue;
long rememTime;
int relayState =0;

void setup() {
  pinMode(relayPin, OUTPUT);// define relayPin  as output
  pinMode(resetPin, INPUT_PULLUP);// define input pin with pullup (watch video)
  pinMode(startPin, INPUT_PULLUP);// define input pin with pullup (watch video)
  attachInterrupt(digitalPinToInterrupt(resetPin), reset, LOW);
    
  Serial.begin(9600);// initialize serial monitor with 9600 baud
  if(relayType == 'L')
  {
    digitalWrite(relayPin, HIGH);// turn the relay OFF and keep it OFF
      Serial.println("......"); 
      Serial.println("Relay Type: LOW Trigger");      
  }else{
    digitalWrite(relayPin, LOW);// turn the relay OFF and keep it OFF
      Serial.println("......"); 
      Serial.println("Relay Type: HIGH Trigger");
  }  
}

void loop() {
  potValue = analogRead(potPin)/10;// reads the value of the potentiometer (value between 0 and 1023)

  duration = map(potValue, 0, 102, minTime, maxTime);// convert A0 value to time set at minTime and maxTime
  
    if(digitalRead(startPin) ==LOW)
    {
     rememTime = millis();
     relayState = 1;
     controlRelay();// send command to turn the relay ON
    }
   if(  (millis()- rememTime) > duration )
   {
    relayState = 0;
    controlRelay();
   }
      Serial.print("Time: ");
      Serial.print(duration/1000);
      Serial.println(" Seconds");     
 delay(200); // wait for 200 milliseconds    
}// loop end


/*
 * 
 * @brief Turns the relay ON or OFF 
 * @param none
 * @return no return value
 */

 void controlRelay()
 {
  if(relayType == 'L')
  {
     if(relayState == 1)
     {
    digitalWrite(relayPin, LOW);// Turn ON relay
      Serial.print("LT-Relay ON for ");
      Serial.print(duration/1000);// display in seconds
      Serial.println(" Seconds");
     }else{
    digitalWrite(relayPin, HIGH); // turn OFF
      Serial.println("====Relay is OFF");
     }
      
  }else{
     if(relayState == 1)
     {    
      digitalWrite(relayPin, HIGH);
      Serial.print("HT-Relay ON for ");
      Serial.print(duration/1000);// display in seconds
      Serial.println(" Seconds");  
     }else{
      digitalWrite(relayPin, LOW); 
      Serial.println("==Relay OFF");  
     }  
  }

}//controlRelay end




void reset()
{
  duration =0;
   if(relayType == 'L')
  {
    digitalWrite(relayPin, HIGH);// turn OFF High trigger relay     
  }else{
    digitalWrite(relayPin, LOW);// turn OFF Low trigger relay
  
  } 
  Serial.println("Relay OFF"); 

}//reset()

Hello ash2002
It seems to be a school assigment, isn´t it?
Post your sketch, well formated, with comments and in so called code tags "</>" and schematic to see how we can help.
Have a nice day and enjoy coding in C++.

1 Like
const byte triggerInputPin  = 2; // your start-pin
// reset is done by the code: a monoflop resets ITSELF
const byte triggerIsActive = LOW; // shall triggering happen if trigger-input is LOW or HIGH?

const byte PinToSwitch     = 8; // your relay-pin
const byte OutPutOn  = HIGH;    // is output "active" with IO-pin beeing LOW or HIGH?

// the attention-mark ! is the not-operator which inverts the value
// !true = false  !false = true     !HIGH = LOW    !LOW = HIGH
const byte OutPutOff = !OutPutOn; 

// set InitialWaitTime to 0 if you don't want a delay between triggering and switching output
unsigned long InitialWaitTime = 2000; // set to zero if you don't want an initial wait
unsigned long ActiveTime = 3000;
unsigned long LockedTime = 10000; // set to zero if you don't want a lock-time

unsigned long MonoFlopTimer; // variable used for non-blocking timing

// constants of the state-machine
const byte sm_Idling      = 0;
const byte sm_InitialWait = 1;
const byte sm_Activated   = 2;
const byte sm_Locked      = 3;

byte MonoFlopState = sm_Idling; // state-variable of the state-machine


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("  compiled ") );
  Serial.print( F(__DATE__) );
  Serial.print( F(" ") );
  Serial.println( F(__TIME__) );
}


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}

unsigned long MyTestTimer = 0;                   // Timer-variables MUST be of type unsigned long
const byte    OnBoard_LED = 13;


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);

  if ( TimePeriodIsOver(MyBlinkTimer, BlinkPeriod) ) {
    digitalWrite(IO_Pin, !digitalRead(IO_Pin) );
  }
}


void setup() {
  Serial.begin(115200);
  Serial.println("Setup-Start");
  PrintFileNameDateTime();
  pinMode(triggerInputPin,INPUT_PULLUP); // INPUT_PULLUP
  digitalWrite(PinToSwitch,OutPutOff);
  pinMode(PinToSwitch,OUTPUT);
}


void MonoFlopStateMachine() {

  switch (MonoFlopState) {

    case sm_Idling:
      // check if trigger-input reads triggering signal
      if (digitalRead(triggerInputPin) == triggerIsActive) {
        MonoFlopTimer = millis();       // make snapshot of time
        MonoFlopState = sm_InitialWait; // set next state of state-machine
        Serial.println( F("trigger-signal detected start inital wait") );
      }
      break; // IMMIDIATELY jump down to END OF SWITCH

    case sm_InitialWait:
      // wait until initial waittime has passed by
      if ( TimePeriodIsOver(MonoFlopTimer,InitialWaitTime) ) {
        // if waittime HAS passed by
        MonoFlopTimer = millis();           // make new snapshot of time
        digitalWrite(PinToSwitch,OutPutOn); // switch IO-Pin to activated state
        MonoFlopState = sm_Activated;       // set next state of state-machine
        Serial.println( F("InitialWaitTime is over switching output to ACTIVE") );
      }
      break; // IMMIDIATELY jump down to END OF SWITCH

    case sm_Activated:
      // check if time the IO-pin shall be active is over
      if ( TimePeriodIsOver(MonoFlopTimer,ActiveTime) ){
        // if activetime of IO-pin IS over
        MonoFlopTimer = millis();             // make new snapshot of time
        digitalWrite(PinToSwitch,OutPutOff);  // switch IO-pin to DE-activated state
        MonoFlopState = sm_Locked;            // set next state of state-machine
        Serial.println( F("Activetime is over switching output to IN-active") );
        Serial.println( F("and starting locktime") );
      }
      break; // IMMIDIATELY jump down to END OF SWITCH

    case sm_Locked:
      // check if time the logic shall be locked against too early re-triggering is over
      if ( TimePeriodIsOver(MonoFlopTimer,LockedTime) ){
        // if locked time IS over
        Serial.println( F("locktime is over change state to idling") );
        MonoFlopState = sm_Idling; // set state-machine to idle-mode
      }
      break; // IMMIDIATELY jump down to END OF SWITCH
  } // END OF SWITCH
}


void loop() {
  BlinkHeartBeatLED(OnBoard_LED, 250);

  // run down code of state-machine over and over again
  // all the logic for reading in sensor-signal and switching output ON/OFF 
  // is inside the function
  MonoFlopStateMachine(); 
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.