Unofficial answer: Absolute value and code help

For @Sgarg14, answering Absolute value and code help
While everyone here uses the notation of:


while(<some condition>)  {
    motor<some motor>] = 127;
}

it makes little sense and leads exactly to the problem you observe. Your motor never stops because you never command it so.
But you do keep telling it to go 127. And again, and again. If the motor was a teenager, it would be shouting at you at the third iteration of the loop (thus within microseconds, as written): “Heard ya, K?”

What you actually want to do is more like:


motor<some motor>] = 127;
while(<some condition>)  {
 // well, really do nothing here. The motor got the command, you are just waiting for the condition to stop it afterward
}
motor<some motor>] = 0;

Or, using natural language


motor<some motor>] = 127;
waitUntil(<some condition>) ; // this looks so much more logical, semantic-wise
motor<some motor>] = 0;

So to fix your program, just add that “motor[rightmotor] = 0;” at proper places.

On a more general note, the code structured as in the first sample has some value, when used with little more logic inside.
Consider:


while(SensorValue[motorencoder] < 1500)  {
    motor[rightmotor] = calculatePowerBasedOnRemainingDistance(1500-SensorValue[motorencoder]);
}
motor[rightmotor] = 0;

The code like that has few benefits:

  • It doesn’t start the motor momentatily (jitter) if the condition has already passed
  • Can actually vary the power during the “wait” based on some more complex state. In my sample, I suggested a slow-down ramp, but it could be a full-blown speed PID, algorithm for straight driving, more complicated speed profile and whatnot…