I'm running a program using ncurses with a loop that is supposed to generate a window for character movement, wait ~five seconds, clear the window, and start again. My thought is to have this be in a nested window that will do this ten times. However, after the first five seconds ends, the entire loop is broken and the program finishes.
int i=0;
while(i < 10)
{
playwin.makeWindow();
wtimeout(playwin.getWindow(), 0);
originalTime = time(NULL);
while(newTime < 5)
{
newTime = time(NULL);
newTime -= originalTime;
player.display();
playwin.drawWindow();
player.getMv();
}
wclear(playwin.getWindow());
i++;
}
I expect that the window gets made, the wtimeout function will stop the getMv function from blocking, the nested while loop will display the window and allow the player to move around. After about five seconds, I expect that while loop to end, the window to get cleared, the iterator to increase, and for the loop to start again.
However, after the nested while loop ends, the iterator is already at 10 (verified with printf), so the whole loop breaks.
However, after the nested while loop ends, the iterator is already at 10 (verified with printf), so the whole loop breaks.
there is no visible initialization of newtime, if its initial value (may be undefined if there is no init at all) is not less than 5 the while(newTime < 5)... is never executed because newTime never changes and i become quikly 10
If its initial value if less than 5 the while(newTime < 5)... is only executed one time because you do not reset its value after
Just add for instance newTime = 0; (or a value less than 5) before while(newTime < 5) ...
Before you enter the loop, originalTime is set to the current time.
As soon as you enter, newTime gets (probably) the same value.
You substract one from the other so newTime becomes 0.
It will therefore not enter the loop a second time.
Related
I am a complete coding noob but I am trying to get all LED's to flash on and off 5 times while specifically using a for loop (it has to be a for loop).
The LED in question is attached to a bus (also has to be the case) with the integer assignment of 76.
EDIT: When I try a simple for loop with a counter of 5 and then turn the LED's on and off in the statement it only does it once. It may be simpler to assign my LED flashes to the count in the for loop if this is possible?
My thinking so far is to either design a for loop to repeat the same number two numbers 5 times (76 and 0) and assign the bus to the count in the statement however I am struggling to get my head around how to do this only 5 times (My mind can only perceive creating a nested loop endlessly repeating) or to somehow nest a for loop with the operation I want on the inner loop counting off of the outer loop.
Can anyone tell me if I'm on the right track and if so how to either run my first idea only 5 times or assign my Bus actions to my outer loop for the second?
Code so far is below but I have only managed to get the LEDs to turn on.
PortOut traffic(PortC, 0b0000000001001100);
// The default flash rate is once per second for all tasks
int main()
{
int i;
int b;
traffic = 0;
// 1. Flash the ALL the LEDs 5 times using a for loop, when finished the LEDs must be OFF
for (i = 0; i < 5; i= i + 1)
{
(printf("i%d\n", i));
for (b = i; b < 5;)
{
traffic = 76;
wait_us(1000000);
traffic = 0;
}
}
Many thanks in advance,
Joe.
Tried nesting a for loop to repeat the same two integers 5 times in order to assign the Bus to the count,
Only managed to endlessly repeat for loop.
Tried nesting a for loop to count to 5 on the outer loop and flash LED's on the inner loop,
Only managed to switch LED's on once.
Your outer loop is counting the quantity of pulses.
The contents of the loop determine the frequency that an LED is on or off:
for (int counter = 0; counter < 5; ++counter)
{
// Turn on the LEDs
traffic = 76;
// Wait while the LEDs are on.
waitus(1000000);
// Turn OFF the LEDs
traffic = 0;
// Wait while the LEDs are OFF.
waitus(1000000);
} // End of a pulse
The issue is that you a delay after you turn them on and after the LEDs are turned off. You can adjust the different delay amounts; they don't need to be on and off at the same time. The delays should be able to adjust the brightness also.
bool IsGameEnded()
{
static int i = 0;
i++;
if (i == 10)
return true;
return false;
}
int main()
{
bool GameEnd = false;
float ElapsedTime = 0;
while(!GameEnd)
{
chrono::steady_clock::time_point StartingTime = chrono::steady_clock::now();
if (ElapsedTime > 10)
{
ElapsedTime = 0;
draw();
}
GameEnd = IsGameEnded();
chrono::steady_clock::time_point EndingTime = chrono::steady_clock::now();
ElapsedTime = ElapsedTime + chrono::duration_cast<chrono::milliseconds>(EndingTime - StartingTime).count();
}
return 0;
}
I wan't to make a snake game. It will be based on time. For example screen will update every 5 seconds or so. For that I used chrono library. I am not used to this trying o learn it so I might have missed something obvious. But the problem is main function doesn't get get into the if block. So it draws nothing to the console.
I tried debugging (with running line by line). It is not actually like a running program becasue time intervals get long but it enters if block every time. Also if I make the if condition 2 nanoseconds it also works but since cout function can not print so fast I need it to be a lot longer than that. While Debugging I also realised that "StartingTime" and "EndingTime" variables don't get initiated (unless I directly stop on them) . The interesting part is If ı add cout after if block, after a while program starts entering the If block.
When you do:
chrono::duration_cast<chrono::milliseconds>(EndingTime - StartingTime).count();
not enough time has passed, and the count of milliseconds always returns 0. This means you always add 0 to ElapsedTime and it never crosses 10.
One fix is to use a smaller resolution:
chrono::duration_cast<chrono::nanoseconds>(EndingTime - StartingTime).count();
as you mentioned in the question, and adjust the if condition appropriately.
However, the best fix would be to change ElapsedTime from a float to a chrono::duration (of the appropriate unit) since that is the unit that the variable represents. This would let you avoid having to do .count() on the duration as well.
I want to make a program in which there are two dots blinking (with a break of 10ms) simultaneously, but one with delay 200ms and other with delay of 300ms. How can I play these two dots simultaneously from beginning? Is there a better way to that from following:
for(int i=1;i<100;i++)
{
if (i%2==0)
circle(10,10,2);
if (i%3==0)
circle(20,10,2);
delay(10);
cleardevice();
delay(100);
}
I would do something like this instead:
int t0=0,t1=0,t=0,s0=0,s1=0,render=1;
for (;;)
{
if (some stop condition like keyboard hit ...) break;
// update time, state
if (t>=t0) { render=1; s0=!s0; if (s0) t0+=10; else t0+=200; }
if (t>=t1) { render=1; s1=!s1; if (s1) t1+=10; else t1+=300; }
// render
if (render)
{
render=0;
cleardevice();
if (s0) circle(10,10,2);
if (s1) circle(20,10,2);
}
// update main time
delay(10); // Sleep(10) would be better but I am not sure it is present in TC++
t+=10;
if (t>10000) // make sure overflow is not an issue
{
t -=10000;
t0-=10000;
t1-=10000;
}
}
Beware the code is untested as I wrote it directly in here (so there might be syntax errors or typos).
The basic idea is having one global time t with small enough granularity (10ms). And for each object have time of event (t0,t1) state of object (s0,s1) and periods (10/200 , 10/300).
If main time reach the event time swap the state on/off and update event time to next state swap time.
This way you can have any number of objects just make sure your main time step is small enough.
The render flag just ensures that the scene is rendered on change only.
To improve timing you can use RDTSC instead of t+=10 and actually measure how much time has passed with CPU frequency accuracy.
To display the two circles simultaneously in the first round, you have to satisfy both conditions i%2==0 and i%3==0 at once. You can achieve it by simply changing
for(int i=1;i<100;i++)
to
for(int i=0;i<100;i++)
// ↑ zero here
I'm trying to determine if five seconds have passed in a console application since the last time I checked. I think my logic is slightly off and I don't know how to resolve it.
My lastCheck variable is firstly 0 when the program begins. It's responsible for holding the "old time".
LastCheck is updated by CheckSeconds(), which gives it a new "old time"
If the LastCheck was equal to 1232323, and the now variable is currently equal to 1227323 then I would know 5000 milliseconds have passed. (in reality, the numbers are much greater than this)
Else, I don't want anything to happen, I want to wait until these five seconds have actually passed.
BACKEND
inline std::vector<int> CheckSeconds(int previous, int timeinseconds)
{
//check if a certain amount of seconds have passed.
int now = GetTickCount();
int timepassed = 0;
std::vector<int> trueandnewtime;
//if the current time minus the old time is greater than 5000, then that means more than 5000 milliseoncds passed.
//therefore the timepassed is true.
if (now - previous > 5000)
timepassed = 1;
trueandnewtime.push_back(timepassed);
trueandnewtime.push_back(now);
return trueandnewtime;
}
FRONTEND
storage = CheckSeconds(LastCheck, 5);
LastCheck = storage.at(1);
if (storage.at(0) == 1)
{
....blahblahblah.....
}
Anyone know what I'm doing wrong? I must have a logic error somewhere or I'm being dumb.
Also worth noting, this code is in a while loop, getting constantly run at Sleep(60); It's a console application at the momemnt.
Appreciate any assistance.
Fixed it by putting the Lastcheck set into the loop.
I have a while loop that runs in a do while loop. I need the while loop to run exactly every second no faster no slower. but i'm not sure how i would do that. this is the loop, off in its own function. I have heard of the sleep() function but I also have heard that it is not very accurate.
int min5()
{
int second = 00;
int minute = 0;
const int ZERO = 00;
do{
while (second <= 59){
if(minute == 5) break;
second += 1;
if(second == 60) minute += 1;
if(second == 60) second = ZERO;
if(second < 60) cout << "Current Time> "<< minute <<" : "<< second <<" \n";
}
} while (minute <= 5);
}
The best accuracy you can achieve is by using Operating System (OS) functions. You need to find the API that also has a callback function. The callback function is a function you write that the OS will call when the timer has expired.
Be aware that the OS may lose timing precision due to other tasks and activities that are running while your program is executing.
If you want a portable solution, you shouldn't expect high-precision timing. Usually, you only get that with a platform-dependent solution.
A portable (albeit not very CPU-efficient, nor particularly elegant) solution might make use of a function similar to this:
#include <ctime>
void wait_until_next_second()
{
time_t before = time(0);
while (difftime(time(0), before) < 1);
}
You'd then use this in your function like this:
int min5()
{
wait_until_next_second(); // synchronization (optional), so that the first
// subsequent call will not take less than 1 sec.
...
do
{
wait_until_next_second(); // waits approx. one second
while (...)
{
...
}
} while (...)
}
Some further comments on your code:
Your code gets into an endless loop once minute reaches the value 5.
Are you aware that 00 denotes an octal (radix 8) number (due to the leading zero)? It doesn't matter in this case, but be careful with numbers such as 017. This is decimal 15, not 17!
You could incorporate the seconds++ right into the while loop's condition: while (seconds++ <= 59) ...
I think in this case, it would be better to insert endl into the cout stream, since that will flush it, while inserting "\n" won't flush the stream. It doesn't truly matter here, but your intent seems to be to always see the current time on cout; if you don't flush the stream, you're not actually guaranteed to see the time message immediately.
As someone else posted, your OS may provide some kind of alarm or timer functionality. You should try to use this kind of thing rather than coding your own polling loop. Polling the time means you need to be context switched in every second, which keeps your code running when the system could be doing other stuff. In this case you interrupt someone else 300 times just to say "are we done yet".
Also, you should never make assumptions about the duration of a sleep - even if you had a real time OS this would be unsafe - you should always ask the real time clock or tick counter how much time has elapsed each time because otherwise any errors accumulate so you will get less and less accurate over time. This is true even on a real time system because even if a real time system could sleep accurately for 1 second, it takes some time for your code to run so this timing error would accumulate on each pass through the loop.
In Windows for example, there is a possibility to create a waitable timer object.
If that's Your operating system check the documentation here for example Waitable Timer Objects.
From the code You presented it looks like what You are trying to do can be done much easier with sleep. It doesn't make sense to guarantee that Your loop body is executed exactly every 1 second. Instead make it execute 10 times a second and check if the time that elapsed form the last time, You took some action, is more than a second or not. If not, do nothing. If yes, take action (print Your message, increment variables etc), store the time of last action and loop again.
Sleep(1000);
http://msdn.microsoft.com/en-us/library/ms686298(VS.85).aspx