Unofficial Response to "Forever Loop"

@Javapower
Original Thread: Forever loop - ROBOTC Tech Support - VEX Forum

I think you are overlooking something very important, but not easy to see (especially if it is your first time).
Problem:
When the program starts the encoders will read 0. Even if the encoder turns, the value the cortex will detect on the on the sensor will still be 0, because it has not been refreshed. Basically, you have only set the sensor to 0, but you have not told it to look for new values so it still thinks it’s at 0 even after rotating. 0 is less than your target distance so the motors will run infinitely.

Solution:
You need the value of the sensor to get updated continuously, so have a forever loop check for the sensor value. Next, you only want to reset the encoder once, so move it out of the drive function you created.
Something like this:


int rightEncoderCount = nMotorEncoder[rearRight]; //create variables to store encoder value
int leftEncoderCount = nMotorEncoder[rearLeft]; //create variables to store encoder value
void drive(int drive1, int drive2, int distance)
{
	//note resetting the encoders has been removed from the drive function
	while(rightEncoderCount < distance || leftEncoderCount< distance){ //notice the variables that store the encoder values are being used to compare to the distance
	motor[frontLeft] = drive1;
	motor[frontRight] = drive2;
	motor[rearLeft] = drive1;
	motor[rearRight] = drive2;
}
	motor[frontLeft] = 0;
	motor[frontRight] = 0;
	motor[rearLeft] = 0;
	motor[rearRight] = 0;
}

task main()
{
SensorValue[rearRightEncoder] = 0; //first reset your encoders
SensorValue[rearLeftEncoder] = 0;
	while(true){ 
		int rightEncoderCount = nMotorEncoder[rearRight]; //now the encoder value will refresh and be stored in the variable
		int leftEncoderCount = nMotorEncoder[rearRight]; //now the encoder value will refresh and be stored in the variable
		drive(100,100,180); //encoders have 360 counts per revolution, so if the code works then the encoder should rotate about half way around and stop
	}
}


Thank you, and I hope this helps :slight_smile:
Please note, I’m still a novice with RobotC, so there may be small errors in the code. I also wrote this on a computer that doesn’t have RobotC installed, so I was unable to have robotC debug it for any errors

You may want to have a look at the code again. The OP is using nMotorEncoder as part of the while loop, this is correct, you have changed this loop to use variables (rightEncoderCount and leftEncoderCount) that won’t be updated, remember the while loop inside the drive function will not exit until the expression it evaluates is true.

In the RobotC debugger window, can you see both encoder values changing? If either one isn’t, that’s your problem. If both do change, then I don’t know what the cause of the problem is.