Defining PROS Objects Outside Of Functions

Out of curiosity, I decided to test to see if defining functions outside of the normal functions would work since copying and pasting everything makes it a little disorganized and a little tedious.

For example:

/* <<#include stuff goes here>> */

pros::Controller master (pros::E_CONTROLLER_MASTER);

pros::motor frontLeft (1);
pros::motor frontRight (2);
pros::motor backLeft (3);
pros::motor backRight (4);

pros::motor_group left ({frontLeft, backLeft});
pros::motor_group right ({frontRight, backRight});

int joystickR = master.get_analog(ANALOG_RIGHT_Y);
int joystickL = master.get_analog(ANALOG_LEFT_Y);

void opcontrol() {
        while (true){
                if (joystickR > 5 || joystickR < -5 || joystickL > 5 || joystickL < -5){
                        right.move(joystickR);
			left.move((joystickL);
		}
        }

However, when I applied it to the code, the bot wasn’t responding at all. Is there a way to define the objects once in the code? Or does it have to be defined within the functions?

For clarification, I meant “defining PROS objects” not “defining functions.”

Which file is this? Are there any other files in the project?

This is main.cpp, and it’s the only file in the project.

There are 2 problems with your code:

  1. you have no delay in your while loop. this means that you are starving the brain of any time to do background processes, so your code will just not do anything. please put a pros::delay(10) inside of the while loop

  2. You are setting the joystickR and joystickL values outside of the while loop (not to mention calling the get_analog method from outside of a function, meaning this did not compile in the first place). You should have int joystickR = 0; outside of opcontrol, and then inside of the while loop do joystickR = master.get_analog(ANALOG_RIGHT_Y);

let me know if that doesn’t work.

2 Likes

There are two main issues in your code. The first issue is here:

This code should be inside the while (true) loop, because right now your program only checks the joystick values at the start of the code and then never updates the joystickR and joystickL values ever.

The second issue is in the while loop:

Any time you have a loop that is supposed to run for a long time in PROS, you should include a delay statement inside the loop at the end, so your code will look like this:

void opcontrol() {
        while (true){
                if (joystickR > 5 || joystickR < -5 || joystickL > 5 || joystickL < -5){
                        right.move(joystickR);
			left.move((joystickL);
		}
        pros::delay(5); //waits for 5ms, motors can't update any faster
        }
2 Likes

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