Hello everyone!
I have a problem with my code, and I’m not sure where to start, as the error doesn’t give me much information (or rather, I don’t agree with the error).
I have a sketch where I’m using thread()
to create a new thread to play back morse code via a recursive function to get the timing right. The code works through an array of morse characters, plays back the current one, then deletes it and calls itself after a defined break to continue working through the queue. If there are no characters in the queue, it waits for 100ms, then tries again. That’s the recursion part.
The problem is, after 4330 - 4340 recursive calls (tried 8 times with different delays, always within this range) the code crashes with “StackOverflowError: This sketch is attempting too much recursion
”. There are maybe 8 calls per second, but I tried it with both 1000 calls per second and 4 calls per second, the error always appears after ~4330 calls. My memory isn’t full and the cpu load is ~0%. Which leads me to think that there is some sort of internal limit on how many recursive calls you can have?
I used thread() and recursion because it seemed elegant and efficient, but now I’m stuck at this error and not sure how to solve this. My code needs to run stable over prolonged periods of time, and I’m glad I caught this. Can I somehow “clear the recursion stack”? Start it over? The function does not depend on any parameters or its previous function call (outside of variable assignments).
I recreated the sketch without functionality, just the recursive calls, and now the error message pops up after about 9000 iterations… which is still no good.
Here is the non-functionality code which showcases the problem:
int recursion_count = 0;
void setup () {
//size(600, 400);
// Set up the morse playback thread
thread("morsePlayback");
}
void morsePlayback() {
recursion_count++;
println(recursion_count);
// True for debug reasons
if(0 == 0) {
delay(2);
morsePlayback();
return;
}
// Other functionality, then recursive call
morsePlayback();
return;
}
The original code, crashing after ~4340 calls can be found here.
I hope my question became clear, if not I’ll try to sum it up again: My code crashes after X recursive calls, even though they are spread far apart. Why is that and how I can prevent that?
Thank you for your time already, if I can provide further information please ask!