1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: How to make a timer in C++

  1. Dec 1, 2014 #1
    Basically within my whole code is 4 major chunks of code that each loop repeatedly. The obvious problem is when I run it, it will get stuck on the first chunk and loop forever, therefore never moving on the next chunk. What I need is to have each section run for 10 seconds and then move on. Is there a simple function that could do this?

    Thanks a bunch!
  2. jcsd
  3. Dec 1, 2014 #2


    Staff: Mentor

    why can't you restructure your code with a main loop so that you do one iteration for each of the four chunks?

    or does the subsequent chunks depend on the first chunk to be completed?

    As an example

    Code (Text):

    for(int i=0; i<max; i++) {
  4. Dec 1, 2014 #3
    I need more than one iteration from each chunk at a time. They are blinking LEDs and need to be blinking for a certain amount of time before moving on to the next LEDs (simplified but you get the idea).
  5. Dec 1, 2014 #4


    Staff: Mentor

    How is your program determining how long 10 sec. is? What OS are you using? The reason I ask is that the OS might have some APIs that you can use to do this, which would probably be better than you having an empty loop run for a set amount of time that you determine by trial and error.
  6. Dec 1, 2014 #5


    Staff: Mentor

    look for a sleep function

    so you set your LEDs then sleep then set them differently then sleep ...
  7. Dec 2, 2014 #6
    Hmm. Maybe not what people suggested. Would do the following (and maybe this is what you want):
    Code (Text):
    unsigned char cur_loop = 0; // an index.
    unsigned char loop_count = 4; // you have four loops.
    long interval = 10000 // 10000, assuming milliseconds, stand for 10 seconds per loop.
    long time = current_system_time(); // use whatever type best suits your needs (or the underlying implementation).
    while (true) {
      if (current_system_time() - time > interval) {
        cur_loop = (cur_loop + 1) % loop_count;
      switch (cur_loop) {
         // cases and their blocks here (the magic happens here!)
    // Be warned of the overhead of current_system_time()!
    Copying and pasting this will not do much. I suggest C++11 and the chrono library. Read the documentation. Good luck.
    If you need to repeat for n seconds then go ahead a sleep function won't work without multithreading (noob here, so I may be wrong).
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted