BigRedMachine
BigRedMachine

Reputation: 155

Running more than one delay at the same time ? (C)

I'm trying to write this program where anytime a sensor is triggered I want to have a delay of lets say 3 seconds then do some action, that should be very simple.

Ideally it should go (sensor triggered) 3... 2... 1... (Do Something), what I'm struggling with is the scenario where countdown begins 3... 2... (sensor triggered again) 1... (Do Something) , now that's where things fall apart because I need another delay to begin the countdown from 3 concurrently but I don't know how to achieve that. I wish I could post that part of the code but the entire thing is linked together. Is there a way to do this with a simple C code or does this need advanced techniques ?

Upvotes: 0

Views: 180

Answers (2)

0___________
0___________

Reputation: 68059

There are many ways:

  1. Use threads. The sensor thread will read the sensor and the sleep for 3 seconds.
  2. Use not blocking delays
unsigned getTick(void); // for example 1000 ticks per second

vooid foo(void)
{
    unsigned sensor1StartTime = 0;

    while(1)
    { 
        if(!sensor1StartTime || (getTick() - sensor1StartTime >= 3000))
        {
            handleSensor1();  // it will be executed every ~three seconds
            sensor1StartTime = getTick();
        }
        // do something else 
        // "something else" will not be blocked by delay.
    }
}

Upvotes: 2

kadina
kadina

Reputation: 5372

Whenever a sensor triggers, start a thread, delay (do your count down) and do some thing (whatever you want to do) inside the thread function.

Upvotes: 1

Related Questions