Serial data Event

Hello,

I am working on a task which on's a relay after some time when a serial interrupt is occurred. I don't want to on the relay as soon as the serial interrupt is occurring so i have gave a delay of 5 second so that the relay will on after 5 second's it works well. But further i want to off the relay when the next serial event occurs and vis-versa . so i have used flags so that it shall go to next task only if the flag is high .

void serialEvent() {
  while (Serial1.available()) {

while(onFlag==1)
  {
    Serial.print("On flag");
  delay(5000);
  digitalWrite(relay,HIGH);
  delay(500);
   offFlag = 1;
    onFlag = 0;
    
    }
while(offFlag==1)
  {
  Serial.print("Off flag");
delay(10000);
digitalWrite(relay,LOW);
  delay(500);
   
   offFlag = 0;
   onFlag = 1; 

    
  }

  
  }

The thing is that serial data has to be continuous until the relay is on or off . The problem i am facing is that serial interrupt acts independent so the flags get high and it goes in next loop any suggestion how could i off the serial data or prevent the task to go in next loop.

Your post refers several times to serial interrupt but that is not how serialEvent() works. The function is called at the end of loop() if there is any data in the serial buffer.

To compound your problem, using delay() causes the program to pause completely for the delay period. In order to continue to monitor whether serial data is received during a period of waiting you will need to use millis() for timing as in the BlinkWithoutDelay example in the IDE.

Save the time at which an event occurs and check each time through loop() whether the required period has elapsed. Do not use any functions that block the free running of the loop() function.

Thanks for the help UKHeliBob got want you are saying will try and post what i have done.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R