[Vex C++] Vision Sensor

I was wondering if anyone had any ideas on what to use the vision sensor for. Right now I have it programmed to detect the flags and align itself with them but it takes to long and over corrects. If anyone has code that makes itline up faster that would be much appreciated.

My code:

while(not linedup) {

    Vision.takeSnapshot(SIG_1);
    
    if(Vision.objectCount > 0) {
        
        if(Vision.largestObject.centerX < screen_middle_x -5) {
            
            FLeftMotor.spin(directionType::rev);
            LeftMotor.spin(directionType::rev);
            FRightMotor.spin(directionType::fwd);
            RightMotor.spin(directionType::fwd);
        }
        
        else if(Vision.largestObject.centerX > screen_middle_x + 5){
            
             FLeftMotor.spin(directionType::fwd);
            LeftMotor.spin(directionType::fwd);
            FRightMotor.spin(directionType::rev);
            RightMotor.spin(directionType::rev);
            
        }
        
        else {
            
            FLeftMotor.stop(brakeType::brake);
            LeftMotor.stop(brakeType::brake);
            FRightMotor.stop(brakeType::brake);
            RightMotor.stop(brakeType::brake);
            
        }
    }

That method of aligning with an object (Bang-Bang) is not very good. The above issues of oscillation and slowness are a result of that, because it can not dynamically adjust speed as needed.

Instead, you want to use Proportional (P) control, a member of PID control.
In short, you want the robot to turn faster the more an object is offset from the center of the vision, and slower the closer the robot is to the goal.
You can do this by


motors = (Vision.largestObject.centerX - screen_middle_x) * kP;

This means that if the object is exactly in the middle of the vision, and for example the middle is 50px, then the above evaluates to


(50-50)*1 = 0 Power

However, if the object is a bit to the right of the center, then the motor power will scale up proportionately to the error, and likewise if the object is to the left.
All you need to do is tune the scaling factor


kP

There is a document on PID here.
This is how we were able to get such smooth control on this demo:

The code is available here:

I hope this is useful!

It may be over correcting because you simply have the robot going in a direction with no control to the speed, so when the robot changes direction, it can not slow down fast enough. Also, I would also use PIDs to control motor speeds.