Example of Vex pro v5 callback

I am working on a code as a side project and was told I could cut down how long it is by using callback functions. Can anyone show me how a callback function should look? I can’t find any full examples any where.

void spinIntakes() {
     IntakeL.spin();
     IntakeR.spin();
}
void usercontrol() {
     controller.ButtonL1.pressed( spinIntakes );
}
4 Likes

Thank you, but is there a part that is supposed to go before the
int main( )
How do I set that up?

nope, this is very wrong. you do not define functions inside other functions unless you are defining a lambda.

:man_facepalming: Been a while since I’ve done this

Using namespace vex;
void spinIntakes() {
     IntakeL.spin();
     IntakeR.spin();
}
Void usercontrol(true) {
While(true) {
//user code here
     controller.ButtonL1.pressed( spinIntakes );
}
}
Int main(){
Whilte(true){
//Functions are called here
}
}

code that works
using namespace vex;

// just for the example ......
vex::motor IntakeL(PORT1);
vex::motor IntakeR(PORT2);
vex::controller Controller;

void spinIntakes() {
     IntakeL.spin(forward);
     IntakeR.spin(forward);
}

void usercontrol() {
    while(true) {
      //user code here
    
      // sleep a while
      this_thread::sleep_for(20);
    }
}

int main(){
    // register callbacks once only...
    Controller.ButtonL1.pressed( spinIntakes );

    while(true){
      // perhaps something can happen here

      // sleep a while
      this_thread::sleep_for(20);
    }
}
11 Likes

Is there a way I can get the callback for a specific point on the screen rather than a button or generalized screen pressed?

For example I have something like this

while(true){
if (Brain.Screen.pressing()){
int X = Brain.Screen.xPosition();
int Y = Brain.Screen.yPosition();
if ((X >= origin1X && X <= endX) && (Y >= origin1Y && Y <= endY)){
Brain.Screen.clearScreen();
Brain.Screen.setCursor(1,1);
Brain.Screen.setFillColor(black);
Brain.Screen.setPenColor(white);
wait(.5,seconds);
Brain.Screen.print(“Hallway:”);

Is there a way to get that callback in with the coordinates of where the button is pressed?

Doesn’t this already do what you are asking? That would be the X,Y co-ordinate of the “Press”.

Do you mean that you have multiple buttons on the screen and you want to know which button was pressed?

1 Like

Yes and no. I do have multiple buttons on the screen and based on which button is pressed, it takes you to another screen. My main goal is to use a callback to cut down on the amount of coding lines I have because a lot of the buttons/screens is just the same thing copied and pasted

You have a good instinct - “Don’t Repeat Yourself” is one of the mantras good programmers adhere to.

This could be where “object-oriented” programming could help out. Take a look at this post and associated code. It may serve as a path forward for you:

2 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.