Programming instructions

Reference
Project Lead The Way
©
and Carnegie Mellon Robotics Academy
©
/ For use with VEX
®
Robotics Systems
Switch Case 2
Switch Case
task main()
{
bMotorReected[port2]=1;
int turnVar=0;
while(true)
{
if(SensorValue(touch1)==1)
turnVar=1;
if(SensorValue(touch2)==1)
turnVar=2;
switch (turnVar)
{
case 1:
motor[port3]=-127;
motor[port2]=127;
turnVar=0;
break;
case 2:
motor[port3]=127;
motor[port2]=-127;
turnVar=0;
break;
default:
motor[port3]=127;
motor[port2]=127;
}
}
}
The touch sensors are used to set the value of turnVar in the program below. The switch-case
statement is then used to determine what to do, based on its value. No sensors pressed will
leave turnVar with a value of 0, and the robot will run the “default” case and go straight. Pressing
touch1 will give turnVar a value of 1, and make case 1 run (left turn). Pressing touch2 makes
turnVar 2, which makes case 2 (right turn) run. Both turns reset turnVar to 0 before ending, to
allow fresh input on the next pass of the loop.
Switch statement
The “switch” line designates the value that will
be evaluated to see if it matches any of the case
Case statement
The rst line of a case includes the word “case” and
a value. If the value of the “switch” variable (turnVar)
matches this case value (1), the code following the
“case” line will run.
Commands
These commands belong to the case “1”, and will
run if the value of the “switch” variable (turnVar) is
equal to 1.
Break statement
Each “case” ends with the command break;
Default case statement
If the “switch” value above did not match any of the
cases presented by the time it reaches this point,
the “default” case will run.
Go to Reference Links