C++ Timer control - c++

I want to create a timer so that after completing the time(suppose 10 sec) the control should come out of the function..Please note that am starting the timer inside the function.Code is given below..I want to give certain time limit to that function so that after completing the time the control should come out of the function..I don't want to calculate the time..I want to give my own time so that the function should complete its execution within that time period..suppose if function is waiting for an input then also after completing time limit the control should come out indicating that "time has expired"..once it comes out of the function then it should continue with the next function execution...Is this possible in c++...
Begin();
// here I would like to add timer.
v_CallId = v_CallId1;
call_setup_ind();
call_alert_ind();
dir_read_search_cnf();
dir_save_cnf();
END();

If the code is linear and the functions called cannot be chopped into smaller pieces, your stuck to letting an external process/thread do the timing and abort the worker thread when the timeout is exceeded.
When you can chop the worker into smaller pieces you could do something like this
Timeout.Start(5000);
while ((TimeOut.TimeOut() == false) && (completed == false))
{
completed = WorkToDo()
}
This is a pattern we frequently use in our embbeded application. The timeout class was in house develop. It just reads the tick counter and looks if the time has passed. An framework like QT or MFC should have such a class itself.

Related

How to call a function every x seconds but be able to do stuff in the meantime

I'm building a tetris game and I need the pieces to fall every x seconds; something like:
while(true){
moveDown();
sleep(x)
}
The problem is, I need to be able to move the pieces left and right in the meantime, i.e., call a function while it's sleeping.
How can I do that in c++?
Both time and key presses can be events which can be used to wait on. On UNIXes you'd use something like poll() with a suitable time for timeout and the input device used to recognize key presses. On other systems there are similar facilities (I'm a UNIX persons and I have never worked on Windows specific stuff although it seems the Windows facilities are actually more flexible). Depending on the result of poll() (timeout or activity on the I/O device in that case) you'd do the appropriate action.
This problem is solvable in multiple ways (another idea that comes to mind is multithreading, but that seems overkill). One approach would be to keep track of the number of "game cycles" and execute some function every n-th cycle like this:
for(int32_t count{1};;count++)
{
if (!count % 5)
{
// do something every 5th cycle
}
// do something every cycle
sleep(x);
}
you can measure how much time has passed since last fall and move piece down after given amount and then reset counter. In pseudo-code it could look like this:
while(true)
{
counter.update();
if(counter.value() == fall_period)
{
move_piece_down();
couter.reset();
}
// rotate pieces
}
If you are using typical implementation of game loop your counter can just accumulate elapsed time since last frame.

Alarm Clock with multi alarms alghoritm C++

I've got a simple C++ task - I need to create an alarm app, which triggers alarms a few times.
For example, there is a text file with lines of time in format: hour minutes
I read these into an array.
My idea is that I create an infinite loop which checks what time is it every 60 seconds. Inside this loops, it checks if time == time_array_element_1 or time == time_array_element_2 etc.
And it check every 60 seconds.
Could you guys help me to decide, maybe there is some more optimal way to do it?
"optimal" strongly depends on what you want to achieve:
If you just want to have an alarm: use an existing app.
If you need to implement it on your own program, use a library that provides timer (e.g., Qt, boost, ...)
If you can't use 3rd party libraries because you're not allowed to (homework?): build your own.
If you don't want or cannot build your own timer library: use that loop approach.
If you want to run the alarm at a particular time every day, you could write an infinite loop that checks whether that time has come. Pseudo-Code:
const int alarm_time
const int sleep_time;
while (true) {
const int current = get_seconds_since_midnight();
if (current - alarm_time < sleep_time) {
alarm();
}
sleep(sleep_time);
}
However, you'd still need to keep this program running all the time.
That's fine if you just want to learn.
But for any other use-case, this task should be handled by the OS (e.g., cron on unix).

Spawn 2 enemies per second in GLUT

I'm making a game in openGL and I want to spawn 2 enemies per second on the screen. The problem is, I'm calling the spawn function inside idle:
idle
{
// ...
world.spawnEnemy();
}
And then, in the spawnEnemy function:
void World::spawnEnemy()
{
Enemy newEnemy, newEnemy2;
float start;
start = glutGet(GLUT_ELAPSED_TIME);
// 1/2 a second passes
while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 500 )
{
;
}
// create enemy
newEnemy();
pushToEnemyList(newEnemy);
// another 1/2 second passes
while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 1000 )
{
;
}
// create enemy
newEnemy2();
pushToEnemyList(newEnemy2);
}
And this is not working, of course. Probably because idle is called everytime and I'm calling a function inside idle that waits for a certain amount of time to pass and then everything starts going wrong. The solution is to do the spawning in the idle function (without calling any function, doing all the logic inside idle), but I don't like this idea. I need to do more things in a certain number of time, for example, my enemies have guns and they will have to shoot n times every second. And if I do all of these directly inside of idle it will become a mess. So, basically, how do I make this work:
idle
{
// ...
world.spawnEnemy();
world.enemyShoot();
// another functionalities that depend on time
}
instead of this:
idle
{
// ...
// logic of spawnEnemy directly here in the idle function
// logic of enemyShoot directly here in the idle function
// logic of another functionalities that depend on time directly here in the idle function
}
There is quite a few ways to do this here the most common:
Measure elapsed time
Simply remember time of last spawn t0 and on each (idle) iteration get current time t. If t0+T<=t then spawn new enemy ans set t0=t. The T is the period of spawning in the same units as the measured time. In your case 500ms.
As mentioned OnIdle Event will take 100% of one CPU core for itself. To remedy this use Sleep(x); where x<<T that will ease up on the CPU load (even Sleep(1); will be a big difference).
To measure time use any OS routine you got available (with high enough accuracy) I am using PerformanceCounter on Windows but there are other alternatives like RDTSC etc ...
Timers
Modern messaging based OS provides timer function which will fire your event periodically (usually with ~1ms accuracy). Just study your API to implement it. Then you just spawn your enemy inside timer event without any other logic or timing code ...
In case you do not have any timers you can fake this by creating thread with code like this inside:
for (;!spawn_exit;)
{
if (spawn_enabled) spawn();
Sleep(T);
}
where volatile bool spawn_enabled=true,spawn_exit=false; are used to control the spawning and stop the thread (before App shutdown) But in this case be careful with multi threaded access in the spawn() function ...

running a background process on arduino

I am trying to get my arduino mega to run a function in the background while it is also running a bunch of other functions.
The function that I am trying to run in the background is a function to determine wind speed from an anemometer. The way it processes the data is similar to that of an odometer in that it reads the number of turns that the anemometer makes during a set time period and then takes that number of turns over the time to determine the wind speed. The longer time period that i have it run over the more accurate data i receive as there is more data to average.
The problem that i have is there is a bunch of other data that i am also reading in to the arduino which i would like to be reading in once a second. This one second time interval is too short for me to get accurate wind readings as not enough revolutions are being completed by the anemometer to give high accuracy wind data.
Is there a way to have the wind sensor function run in the background and update a global variable once every 5 seconds or so while the rest of my program is running simultaneously and updating the other data every second.
Here is the code that i have for reading the data from the wind sensor. Every time the wind sensor makes a revolution there is a portion where the signal reads in as 0, otherwise the sensor reads in as a integer larger than 0.
void windmeterturns(){
startime = millis();
endtime = startime + 5000;
windturncounter = 0;
turned = false;
int terminate = startime;
while(terminate <= endtime){
terminate = millis();
windreading = analogRead(windvelocityPin);
if(windreading == 0){
if(turned == true){
windturncounter = windturncounter + 1;
turned = false;
}
}
else if(windreading >= 1){
turned = true;
}
delay(5);
}
}
The rest of the processing of takes place in another function but this is the one that I am currently struggling with. Posting the whole code would not really be reasonable here as it is close to a 1000 lines.
The rest of the functions run with a 1 second delay in the loop but as i have found through trial and error the delay along with the processing of the other functions make it so that the delay is actually longer than a second and it varies based off of what kind of data i am reading in from the other sensors so a 5 loop counter for timing i do not think will work here
Let Interrupts do the work for you.
In short, I recommend using a Timer Interrupt to generate a periodic interrupt that measures the analog reading in the background. Subsequently this can update a static volatile variable.
See my answer here as it is a similar scenario, detailing how to use the timer interrupt. Where you can replace the callback() with your above analogread and increment.
Without seeing how the rest of your code is set up, I would try having windturncounter as a global variable, and add another integer that is iterated every second your main program loops. Then:
// in the main loop
if(iteratorVariable >= 5){
iteratorVariable = 0;
// take your windreading and implement logic here
} else {
iteratorVariable++;
}
I'm not sure how your anemometer stores data or what other challenges you might be facing, so this may not be a 100% solution, but it would allow you to run the logic from your original post every five seconds.

How can I set tens of thousands of tasks to each trigger at a different defined time?

I'm constructing a data visualisation system that visualises over 100,000 data points (visits to a website) across a time period. The time period (say 1 week) is then converted into simulation time (1 week = 2 minutes in simulation), and a task is performed on each and every piece of data at the specific time it happens in simulation time (the time each visit occurred during the week in real time). With me? =p
In other programming languages (eg. Java) I would simply set a timer for each datapoint. After each timer is complete it triggers a callback that allows me to display that datapoint in my app. I'm new to C++ and unfortunately it seems that timers with callbacks aren't built-in. Another method I would have done in ActionScript, for example, would be using custom events that are triggered after a specific timeframe. But then again I don't think C++ has support for custom events either.
In a nutshell; say I have 1000 pieces of data that span across a 60 second period. Each piece of data has it's own time in relation to that 60 second period. For example, one needs to trigger something at 1 second, another at 5 seconds, etc.
Am I going about this the right way, or is there a much easier way to do this?
Ps. I'm using Mac OS X, not Windows
I would not use timers to do that. Sounds like you have too many events and they may lie too close to each other. Performance and accuracy may be bad with timers.
a simulation is normally done like that:
You are simly doing loops (or iterations). And on every loop you add an either measured (for real time) or constant (non real time) amount to your simulation time.
Then you manually check all your events and execute them if they have to.
In your case it would help to have them sorted for execution time so you would not have to loop through them all every iteration.
Tme measuring can be done with gettimer() c function for low accuracy or there are better functions for higher accuracy e.g. QueryPerformanceTimer() on windows - dont know the equivalent for Mac.
Just make a "timer" mechanism yourself, that's the best, fastest and most flexible way.
-> make an array of events (linked to each object event happens to) (std::vector in c++/STL)
-> sort the array on time (std::sort in c++/STL)
-> then just loop on the array and trigger the object action/method upon time inside a range.
Roughly that gives in C++:
// action upon data + data itself
class Object{
public:
Object(Data d) : data(d) {
void Action(){display(data)};
Data data;
};
// event time + object upon event acts
class Event{
public:
Event(double t, Object o) time (t), object(o) {};
// useful for std::sort
bool operator<(Event e) { return time < e.time; }
double time;
Object object;
}
//init
std::vector<Event> myEvents;
myEvents.push_back(Event(1.0, Object(data0)));
//...
myEvents.push_back(Event(54.0, Object(data10000)));
// could be removed is push_back() is guaranteed to be in the correct order
std::sort(myEvents.begin(), myEvents.end());
// the way you handle time... period is for some fuzziness/animation ?
const double period = 0.5;
const double endTime = 60;
std::vector<Event>::iterator itLastFirstEvent = myEvents.begin();
for (double currtime = 0.0; currtime < endTime; currtime+=0.1)
{
for (std::vector<Event>::iterator itEvent = itLastFirstEvent ; itEvent != myEvents.end();++itEvent)
{
if (currtime - period < itEvent.time)
itLastFirstEvent = itEvent; // so that next loop start is optimised
else if (itEvent.time < currtime + period)
itEvent->actiontick(); // action speaks louder than words
else
break; // as it's sorted, won't be any more tick this loop
}
}
ps: About custom events, you might want to read/search about delegates in c++ and function/method pointers.
If you are using native C++, you should look at the Timers section of the Windows API on the MSDN website. They should tell you exactly what you need to know.