Since you did not specify C ++ 98/03, I assume at least C ++ 11, and thus <chrono> is available. This is consistent with Galik's answer so far . However, I would configure it to more accurately use the capabilities of the <chrono> transformation and without the need to manually enter conversion factors, with the exception of the description of “beats / minutes” or actually in this answer, the opposite: “minutes / bits” ,.
using namespace std; using namespace std::chrono; using mpb = duration<int, ratio_divide<minutes::period, ratio<125>>>; constexpr auto flashDuration = 10ms; auto beginBlink = steady_clock::now() + mpb{0}; while (true) { RS232_SendByte(cport_nr, 4);
The first thing to do is to indicate the duration of the strike, which is "minutes / 125". This is what mpb does. I used minutes::period as a stand for 60 , just to improve readability and reduce the number of magic numbers.
Assuming C ++ 14, I can give flashDuration real units (milliseconds). In C ++ 11, this should be written using this more detailed syntax:
constexpr auto flashDuration = milliseconds{10};
And then a loop: this is very similar to the Galik answer design, but here I only increase the time to start blinking once per iteration, and each time, more precisely 60/125 seconds.
time_point to a specified time_point , unlike a specific duration , ensures that there is no accumulated rounding over time. And, working in units that accurately describe your desired duration interval, there is also no rounding error in terms of calculating the start time of the next interval.
No traffic in milliseconds needed. And there is no need to calculate how long you need to delay. Only the need to symbolically calculate the start time of each iteration.
Um ...
Sorry for choosing Galik's answer , which, in my opinion, is the second best answer next to mine, but it shows an error that my answer not only does not have but is intended to prevent. I did not notice this until I dug a calculator into it, and it is thin enough that testing can skip it.
In response to Galik :
total_wait = 480ms; // this is exactly correct off_wait = 990ms; // likely a design flaw on_wait = -510ms; // certainly a mistake
And the total time iteration takes is on_wait + off_wait , which is 440ms , almost imperceptibly close to total_wait ( 480ms ), which makes debugging very difficult.
In contrast, my answer increases ready (beginBlink) only once and exactly 480ms .
My answer is more plausible for the simple reason that it delegates more of its computations to the <chrono> library. And in this particular case, this probability has paid off.
Avoid manual conversions. Instead, let the <chrono> library do them for you. Manual conversions result in an error.