This is the code you posted properly formatted, with a few house cleaning things.
// this worked fine. Both motors ran independently
task main() {
while(true) {
if(SensorValue(num3)) {
startMotor(mot2, 50);
} else if(!SensorValue(num3)) {
stopMotor(mot2);
}
if(SensorValue(num4)) {
startMotor(mot3, 50);
} else if(!SensorValue(num4)) {
stopMotor(mot3);
}
}
}
// this one was jittery. motors ran slow.
task main() {
while(true) {
if(SensorValue(num3)) {
startMotor(mot2, 50);
} else(!SensorValue(num3)) {
stopMotor(mot2);
}
if(SensorValue(num4)) {
startMotor(mot3, 50);
} else(!SensorValue(num4)) {
stopMotor(mot3);
}
}
}
Where you screwed up is here:
} else(!SensorValue(num4)) {
“else” doesn’t have a parenthesis condition block thing like if does. So what this code does is basically this…
} else {
!SensorValue(num4);
}
stopMotor(mot3);
So when you don’t provide a block to a symbol like else, it’ll work on the next statement you give it. You gave it a statement, (!SensorValue(num4)) which evaluates in the else clause. However what comes next is a block, which will be run as if it’s the next command. Else ingested the (!SensorValue(num4)) statement so it’s done so now in all cases regardless of circumstances the motor is told to stop. Since you are setting the motor and then immediately stopping it you’re getting the jerks.
This is what you wanted…
task main() {
while(true) {
if(SensorValue(num3)) {
startMotor(mot2, 50);
} else {
stopMotor(mot2);
}
if(SensorValue(num4)) {
startMotor(mot3, 50);
} else {
stopMotor(mot3);
}
}
}
Which is safer code in general since you only ever allow the motors to go if the button is pressed. Good defensive programming.
There is a more compact way to do this…
task main() {
while(true) {
startMotor(mot2, SensorValue(num3) ? 50 : 0);
startMotor(mot3, SensorValue(num4) ? 50 : 0);
}
}
This uses ternary operators which work as inline if-else statements. Basically…
SensorValue(num3) ? 50 : 0
Says if the sensor value of num3 is true (non zero), put the first value after the question mark into the startMotor function, else put the second value. The second value is 0 which stops the motor.
Yes yes the statements are harder to read, but it’s so much less code which I think is a readability win.
-Cody