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.

Note:
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(timer.read() > 0.5)  //Unutar ove petlje kako bi smo izbjegli debouncing
    {
        brojac++;

        pokreni_motore();
        timer.reset();
    }
}

The func pokreni_motore();

void pokreni_motore()
{
    if(brojac % 2 == 0)
    {
        flash = 1;
    
        pwm_L.write(0.4);
        pwm_D.write(0.4);
    }
    if(brojac % 2 != 0)
    {
        flash = 0;

        pwm_L.write(0);
        pwm_D.write(0);
    }

}

Main:

int main()
{
    pwm_L.period(0.02);
    pwm_D.period(0.02);


    timer.start();          //debounce
    button.mode(PullUp);
    button.rise(&toggle);
}

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.

Hello,

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