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

1. 2 months ago

### choacher

Dec 7

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);
}

}

}

See post in context

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);
}
}```
2. ### jpearman

Dec 7 Moderator, ROBOTC Tech Support, V5 Beta Moderator Answer Rockstar, Los Angeles 8888
Edited 2 months ago by jpearman

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);
}
}```