# Why is this program inconsistent? Help please....due tomorrow

Students created a machine that lifts a weight. It starts when button is pushed, stops when reaching upper limit, reverses direction on next button push, stops when reaches lower limit switch. This is a continious loop. Problem we are having is direction does not always change. Can you please help me help my students?

{
int countValue=3;

while(1)
{
if(SensorValue[button]==1)////////////////////////////PUSH THE BUTTON IT RUNS ALL MOTORS POSITIVE DIRECTION
{

startMotor(rightMotor,127);
startMotor(leftMotor,127);
startMotor(midMotor,127);

}
else if (countValue %2==0)
{
startMotor(rightMotor,-127);
startMotor(leftMotor,-127);
startMotor(midMotor,-127);

countValue=countValue+1;

}
else if(SensorValue[upper]==1 ||
SensorValue[lower]==1)
{
stopMotor(leftMotor);
stopMotor(rightMotor);
stopMotor(midMotor);
}

}

}

Every time around the loop you test for the button press. The loop is running very fast so you will increment countValue multiple times. You need to detect the change of state from off to on just once. perhaps try something like this.

``````task main()
{
int countValue=3;
int buttonValue = 0;
int lastButtonValue = 0;

while(1)
{
buttonValue = SensorValue[button];

if( buttonValue==1 && lastButtonValue==0 )////////////////////////////PUSH THE BUTTON IT RUNS ALL MOTORS POSITIVE DIRECTION
{
startMotor(rightMotor,127);
startMotor(leftMotor,127);
startMotor(midMotor,127);

}
else
if (countValue %2==0)
{
startMotor(rightMotor,-127);
startMotor(leftMotor,-127);
startMotor(midMotor,-127);

countValue=countValue+1;
}
else
if(SensorValue[upper]==1 || SensorValue[lower]==1)
{
stopMotor(leftMotor);
stopMotor(rightMotor);
stopMotor(midMotor);
}

lastButtonValue = buttonValue;
wait1Msec(10);
}
}
``````