Difference between revisions of "Using switch statements"

From ROBOTC API Guide
Jump to: navigation, search
(Created page with "{{DISPLAYTITLE: Using Switch Statements}} <yambe:breadcrumb self="Using Switch Statements">Programming_Tips_Tricks|Programming Tips Tricks</yambe:breadcrumb> <br /> Here's an...")
 
 
Line 27: Line 27:
 
|}<br />
 
|}<br />
  
This is an example of a struct. If you have multiple arms on your robot, you can have a struct to hold the properties of each one.
 
 
A struct is implemented, and its components are accessed like this:<br />
 
{|
 
|-
 
|<syntaxhighlight lang="ROBOTC">
 
robotArm leftArm;
 
leftArm.maxPos = 2000;
 
leftArm.minPos = 150;
 
leftArm.armSpeed = 100;
 
</syntaxhighlight>
 
|}<br />
 
  
 
{{tip-from-author|name=jpearman|link=http://www.vexforum.com/showpost.php?p=221035&postcount=8}}
 
{{tip-from-author|name=jpearman|link=http://www.vexforum.com/showpost.php?p=221035&postcount=8}}

Latest revision as of 20:31, 15 May 2012

General ProgrammingProgramming Tips Tricks → Using Switch Statements


Here's another tip demonstrating the use of the switch statement.

Let's say you have a motor that you want to drive forward if you press one button and backwards if you press a different button. If you press both or neither buttons the motor should be stopped. You could program this with cascaded if..then..else statements but another way is to combine the two buttons into one variable and use a switch statement. The "<<" is a shift left operator which is often used instead of multiply by 2. DriveLiftMotor would be a function to actually send values to the motor. Everything in capitals are constants defined elsewhere in the code:

// LiftCtl will be 0, 1, 2 or 3 depending on which buttons are pressed
LiftCtl = (vexRT[ LIFT_DN_BUTTON ] << 1) + vexRT[ LIFT_UP_BUTTON ];
 
switch( LiftCtl )
    {
    case    1:  // first button pressed
        DriveLiftMotor( LIFT_UP_SPEED );
        break;
    case    2: // second button pressed
        DriveLiftMotor( LIFT_DN_SPEED );
        break;
    default:  // either neither or both buttons pressed
        DriveLiftMotor( 0 );
        break;
    }


This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=221035&postcount=8.