Hi,
I have just read through your code.
When you accelerate you do so in steps of +1.
When you decelerate you do so in steps of -20, so you pull up quickly.
What is to stop your speed instead of going to Zero but go to -5.
At that point the speed<0 condition is true and it drops out of the while loop.
The code you have that checks of negative speed should be AFTER the -20, and before the end of the while loop.
Like this.
void decelerate()
{
while (Speed > 0) //loop to decelerate to 0 speed
{
readSens(); //read sensors
printReport(); //print report
// if (Speed < 0)
// {
// Speed = 0;
// }
// analogWrite(trainS, Speed); //Sets the speed of the train (255 is ful speed)
Speed = Speed - 20; //subtract 20 of speed
if (Speed < 0)
{
Speed = 0;
}
analogWrite(trainS, Speed); //Sets the speed of the train (255 is ful speed)
delay(decspeed); //slow down the proces
}
}
I hope it makes a difference, its the only thing I can see that may cause the glitch.
I also did an AutoFormat
Tom... ![]()