How to fix a callback function? P.S. Please note I have literally no experience with C++ but I do with Java and Python

I started to try to create a callback function that would make the robot stop instantly, then back up to turn 90 degrees once a button trigger is pressed. My previous version of this was a while statement but that only worked one time and never repeated so I decided to convert it into a callback function. The code below is the original version.

    while(1){
        if(LeftBumper.pressing()){  
        Drivetrain.stop(brake); 
        Drivetrain.turnFor(right, 90, degrees); 
        Drivetrain.drive(reverse);
        }
    }

The callback statement is this:

 void RBumper(){
     while(1){
        if(RightBumper.pressing()){  
            Drivetrain.stop(brake); 
            Drivetrain.turnFor(left, 90, degrees); 
            Drivetrain.drive(reverse);
        }
     }
 }

I’m guessing you dont need the while and if statements in the callback, just the drive train commands

1 Like

I think it only runs once because you’re not creating a complete loop. The program sees the part that you want to execute , but you’re not telling it to loop back in order to execute it again so it just runs it once. If you want it to loop back so it detects if your bumper is pressed down, you should add “return 1;” between the two last brackets. That’ll make it jump back up to the “while(1)” and create a loop.
P.S. you might want to change that “void” to “int” to avoid errors, but I might be wrong.

Fixed loop version:

 void RBumper(){
 while(1){
    if(RightBumper.pressing()){  
        Drivetrain.stop(brake); 
        Drivetrain.turnFor(left, 90, degrees); 
        Drivetrain.drive(reverse);
    }
 }
return 1;
}
1 Like

First, you need to understand the difference between blocking and non-blocking functions.

For example, drivetrain.stop(), and .drive() do not “block” and return to calling function almost instantly, but drivetrain.turnFor() by default “blocks” until it turns for requested number of degrees, unless you pass it a boolean waitForCompletion = false.

Once a bumper button is pressed you issue Drivetrain.stop(), it immediately returns, then .turnFor(), waits until robot turns, and then .drive() sets reverse direction and you immediately check if button is still pressing and would stop if it is. You never return from that while(1) loop which is a problem.

I guess, you really want no callbacks, and just one giant while(1) loop with multiple if() statements inside. If a bumper switch is pressing you want to stop(), then drive back for a few ticks, then turnFor(), then set to drive forward direction without blocking and come back into the main loop again.

Also you need to insert a short sleep() call, for like 1 msec, at the end of the while(1) loop body.

4 Likes