How to count down time in arduino?

Hi everyone, I have a question how to count the time of meeting a certain condition in arduino?
I would like to read the Ibus status and if it is> 1900 and lasts more than 2 seconds, it should give a servo signal of 1750ms and then return to the original 1500ms
I don't know how to make it count down these 2 seconds ... if it's over 1900

My code:

unsigned long timeOfLastChangeServo = 0;
unsigned long timeIBus = 0;

void servoOpen(){
   if(IBus.readChannel(3) > 1900)
   {
    servo.attach(PB4);  
    servo.writeMicroseconds(1750);
    timeOfLastChangeServo = millis();
   }
   else if(millis() - timeOfLastChangeServo > 500 and millis() - timeOfLastChangeServo < 1000)
   {
      servo.writeMicroseconds(1500);
   }
   else if(millis() - timeOfLastChangeServo > 1000)
   {
      servo.detach();
   }

Thank you in advance for your help
Sorry for my English

you need to check the IBus.readChannel(3) continuously
when it goes over 1900, make a note of the start time and set a flag
if it goes below 1900, reset the flag
if the flag is set, check if you have reached your timeout and if so perform you servo signal

you need to decide what happens if the reading stays above 1900 once you have done the servo thing

a state machine is a good way to structure such a code

Think of it as:
"Has not been less than or equal to 1900 for 2 seconds"

void loop()
{
  static unsigned long startTime = 0;

  if (signal <= 1900)
    startTime = millis();  // re-start the timer

  // If the timer expires, the signal has been >1900 for 2 seconds
  if (startTime != 0 && millis() - startTime >= 2000ul)
  {
    // Timer Expired
  }
}
1 Like

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