mikael
mikael

Reputation: 3

How can I print values in C at intervals of 1 sec?

I am trying to build a traffic light simulator which requires that I print green for the first 8 seconds at 1 second intervals, yellow for the next 4 seconds at 1 second intervals and red for the last 8 seconds at 1 second intervals. How can I use time.h to implement this in C?

This is my attempt, but I only get an output that prints green nonstop at intervals which are not 1 second long.

// Traffic light simul`ator

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t start, end;
    double elapsed;
    time(&start);  /* start the timer */
    do {
        time(&end);
        elapsed = difftime(end, start);
        if (elapsed )
        {
            printf("green");
        }
    } while(elapsed < 9);
}   

Upvotes: 0

Views: 2143

Answers (3)

The following seems to work as intended:

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t start, end;
    double elapsed, prev_elapsed = 0.0;
    time(&start);  /* start the timer */
    do
    {
        time(&end);
        elapsed = difftime(end, start);
        if (elapsed >= prev_elapsed+1.0)
        {
            printf("green\n");
            prev_elapsed = elapsed;
        }
    } while(elapsed < 9.0);
}

Here we keep track of the 'current' elapsed time, and the time when the previous one-second tick was noted. When this 'current' elapsed differs from the "previous" elapsed we know that one second (or, more likely, slightly more) has gone by, and we print "green".

Upvotes: 3

user10957435
user10957435

Reputation:

Okay, so I figured out what is going on here.

difftime() returns double. That means, fractional seconds can be returned. If they are (which they probably will be), then that means you have some value in elapsed, which means it will not evaluate to false--even though 1 full second has not yet passed.

If you want elapsed to be greater than 1, then just check for it:

if (elapsed >= 1)
{
    printf("green");
}

That should do the trick.

Upvotes: 0

Engineer
Engineer

Reputation: 119

Your code will just print "green" as fast as it can because if(elapsed) will always happen because the condition is always True. You can use difftime but will need to re-work your code a bit (I think it is adding maybe 2-3 lines). Is there a reason you can't just use sleep? It seems to be a simpler solution: print "green", call sleep(1), repeat 7 more times, move on to printing "yellow", and so on. Hope this helps!

Edit: if(elapsed) is True as long as the value elapsed is not equal to 0, and just because computers don't act instantaneously there will always be a non-zero time difference returned by difftime.

Upvotes: 0

Related Questions