View Single Post
  #8  
Old 10-03-2011, 10:31 AM
jpearman's Avatar
jpearman jpearman is offline
Senior Member
VEX # 8888
 
Join Date: Apr 2011
Location: Los Angeles
Posts: 3,055
Re: RobotC programming tips

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.

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;
        }
Reply With Quote