Function inside a function calls it self after finishing (stuck in recursion)

Device: Nucleo f446re
IDE: mBed studio

With the fall of a button I call a function which calls another function to set the PWM output duty-cycle.

That works great, the duty cycle is set and the wheels start turning. But after only a couple of seconds the wheels suddenly stop turning.

I used the debug function to discover that after the function pokreni_motore() is done running, it goes back to function toggle() from which it was called, but it doesnt continue from the line pokreni_motore() was originally called but it starts from the beginning, as if the function toggle() was called again. And as such the two functions are stuck in a loop calling each other.

The functions loop again even if they shouldnt only when I have already pressed the button and the wheels have started turning (AKA it stops them from turning). But if I havent pressed the button or the functions have looped illegally and have stopped the wheels, the wheels will not start turning and the functions wont be looping.

Here is the code for toggle():

void toggle()
    if( > 0.5)  //Unutar ove petlje kako bi smo izbjegli debouncing


The func pokreni_motore();

void pokreni_motore()
    if(brojac % 2 == 0)
        flash = 1;
    if(brojac % 2 != 0)
        flash = 0;




int main()

    timer.start();          //debounce

To summarize; I want to press a button, have the wheels start turning, press the same button again to make the wheels stop turning. And only have them start/stop when I click the button.

I hope what i wrote makes sense, its 5 in the morning and I have been trying to crack this thing for the last 3 hours. Hope someone sees what I’m missing.


it seems like your code is permanently in interrupts. Try to check

  • your pins for InterruptIn, PwmOut and DigitalOut are different
  • your pins for InterruptIn, PwmOut and DigitalOut are not shared
  • take a look to your button is not broken

BR, Jan

You were right! I switched the code to the Nucleos user button and now works as it should.
A part of me is now wondering what went wrong inside the button to make it randomly send out a signal seconds after being pressed.
Either way, thank you