How to implement one loop with different frequencies - c++

Assume the following while loop runs at 1kHz. What is the proper way to run another piece of code inside this loop but with different frequency (i.e. say 500Hz) without multithreading.
while (1){ // running 1kHz (i.e. outer loop)
do stuff
if (){ // running 500Hz (i.e. inner loop)
do another stuff
}
}
Another question is assume the outer loop runs at the maximum speed of the CPU, is it possible to run the inner loop at a percentage of outer loop (i.e. 50% of outer loop).

The easiest way is something like this:
int counter = 0;
while (1) {
// do stuff
if (++counter == 2) { // inner loop
counter = 0;
// do other stuff
}
}
Note that in a spin-loop like this there's no guarantee that the outer loop will run at 1kHz; it will run at a speed determined by the CPU speed and the amount of work that occurs within the loop. If you really need exactly 1kHz execution, you'll probably want to program a timer-interrupt instead. What is guaranteed is that the code inside the inner if() block will be executed on every second iteration of the outer loop.

Something like this should work
unsigned int counter = 0;
while (1) {
// do stuff
counter+=1;
if ((counter%2) == 0) { // inner loop
// do other stuff
}
}

Related

How do I use a for loop to flash a single LED on and off? (c++) (Mbed Studio) (Nucleo Board)

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.

how to delay a function that is called in a while loop without delaying the loop

imagine I have something like this
void color(int a)
{
if (a > 10)
{
return;
}
square[a].red();
sleep(1second);
color(a+1);
}
while (programIsRunning())
{
color(1);
updateProgram();
}
but with something that actually requires a recursive function.
how can I call this recursive function to color the squares one by one.
because on its own its too fast and if the program is being updated every frame.
they instantly get colored when I want them to get colored one by one (with a delay).
sleep() will cause the current thread to stop. That makes it a bad candidate for human-perceptible delays from the main thread.
You "could" have a thread that only handles that process, but threads are expensive, and creating/managing one just to color squares in a sequence is completely overkill.
Instead, you could do something along the lines of: Every time the program updates, check if it's he appropriate time to color the next square.
const std::chrono::duration<double> color_delay{0.1};
auto last_color_time = std::chrono::steady_clock::now();
bool coloring_squares = true;
while (programIsRunning()) {
if (coloring_squares) {
auto now = std::chrono::steady_clock::now();
// This will "catch up" as needed.
while (now - last_color_time >= color_delay) {
last_color_time += color_delay;
coloring_squares = color_next_square();
}
}
updateProgram();
}
How color_next_square() works is up to you. You could possibly "pre-bake" a list of squares to color using your recursive function, and iterate through it.
Also, obviously, this example just uses the code you posted. You'll want to organise all this as part of updateProgram(), possibly in some sort of class SquareAnim {}; stateful wrapper.
N.B. If your program has little jitter, i.e. it has consistent time between updates, and the delay is low, using the following instead can lead to a slightly smoother animation:
if (now - last_color_time >= color_delay) {
last_color_time = now;
// ...

why dose the first loop always runs faster than the second one?

especially,the larger the number of cycles is,the more obvious the difference becomes.
test in g++ without optimization
int main()
{
int a[]={0,0};
int b[]={0,0};
//first loop
for(unsigned int i=0;i<0x00FFFFFF;i++)
{
a[0]++;a[1]++;
}
//second loop
for(unsigned int i=0;i<0x00FFFFFF;i++)
{
b[0]++;b[0]++; //yes it's b[0] not b[1]
}
return 0;
}
Somebody may not believe me,me either.But in this code the first loop is at least two times faster than the second one.
I suspect it's a pipelining issue. In the first loop you're writing to two different memory locations, so the second addition doesn't need to wait for the first one to finish, and the CPU can do both at once.
In the second loop, you're incrementing the same variable both times, so the second one has to wait for the first one to finish. This slows down the pipeline.

Run two delays at once C++

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

Boost Thread_Group in a loop is very slow

I wanted to use threading to run check multiple images in a vector at the same time. Here is the code
boost::thread_group tGroup;
for (int line = 0;line < sourceImageData.size(); line++) {
for (int pixel = 0;pixel < sourceImageData[line].size();pixel++) {
for (int im = 0;im < m_images.size();im++) {
tGroup.create_thread(boost::bind(&ClassX::ClassXFunction, this, line, pixel, im));
}
tGroup.join_all();
}
}
This creates the thread group and loops thru lines of pixel data and each pixel and then multiple images. Its a weird project but anyway I bind the thread to a method in the same instance of the class this code is in so "this" is used. This runs through a population of about 20 images, binding each thread as it goes and then when it is done looping the join_all function takes effect when the threads are done. Then it goes to the next pixel and starts over again.
I'v tested running 50 threads at the same time with this simple program
void run(int index) {
for (int i = 0;i < 100;i++) {
std::cout << "Index : " <<index<<" "<<i << std::endl;
}
}
int main() {
boost::thread_group tGroup;
for (int i = 0;i < 50;i++){
tGroup.create_thread(boost::bind(run, i));
}
tGroup.join_all();
int done;
std::cin >> done;
return 0;
}
This works very quickly. Even though the method the threads are bound to in the previous program is more complicated it shouldn't be as slow as it is. It takes like 4 seconds for one loop of sourceImageData (line) to complete. I'm new to boost threading so I don't know if something is blatantly wrong with the nested loops or otherwise. Any insight is appreciated.
The answer is simple. Don't start that many threads. Consider starting as many threads as you have logical CPU cores. Starting threads is very expensive.
Certainly never start a thread just to do one tiny job. Keep the threads and give them lots of (small) tasks using a task queue.
See here for a good example where the number of threads was similarly the issue: boost thread throwing exception "thread_resource_error: resource temporarily unavailable"
In this case I'd think you can gain a lot of performance by increasing the size of each task (don't create one per pixel, but per scan-line for example)
I believe the difference here is in when you decide to join the threads.
In the first piece of code, you join the threads at every pixel of the supposed source image. In the second piece of code, you only join the threads once at the very end.
Thread synchronization is expensive and often a bottleneck for parallel programs because you are basically pausing execution of any new threads until ALL threads that need to be synchronized, which in this case is all the threads that are active, are done running.
If the iterations of the innermost loop(the one with im) are not dependent on each other, I would suggest you join the threads after the entire outermost loop is done.