One of the most needed functions in driver mode for a Vex IQ or Vex robot is to keep a motor running continuously for a given function. In this example, we provide you with code to do exactly that. In this example we have a motor connected to port 4 of the Vex IQ Robot Brain. We use two variables. The first, allows only one action per button press. The second, stores the state of the function/motor (e.g. running or stopped). Note: The way this is programmed, if the button is held down, no erratic action of the motor will occur, it will move to the correct state and stay there until the button is released and pressed again.
Be sure to watch the YouTube video which shows this in action!
If you are using Modkit, see our post with code on how to do this in Modkit. Coming soon we will be posting more advanced button latches and eventually how to do this in RobotMesh (Python).
#pragma config(Motor, motor4, conveyorMotor, tmotorVexIQ, PIDControl, encoder) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// /* The program below can be used to latch a function (e.g. motor on/off) with the press of a button. This can be used in driver mode and allows the driver to leave a motor running continuously without having to hold the button down. This can be very useful for axes that require continous motion e.g. a conveyor. */ // define variables // conveyor latch is used to hold conveyor on or off // button one shot is used to allow button action on rising edge, only once per button press bool conveyorMotorLatch = false, BtnRUpOneShot = false; task main() { // Loop forever while(true) { // one-shot if else and one-shot variable allows one action per button press if(getJoystickValue(BtnRUp) == 1 && BtnRUpOneShot == false) { BtnRUpOneShot = true; // if conveyor isn't running then run conveyor if(conveyorMotorLatch == false) { conveyorMotorLatch = true; setMotorSpeed(conveyorMotor, 127); } // else stop conveyor else { conveyorMotorLatch = false; setMotorSpeed(conveyorMotor, 0); } } // else-if the button is released the one-shot is reset to false and the next button press will be accepted else { if(getJoystickValue(BtnRUp) == 0 && BtnRUpOneShot == true) { BtnRUpOneShot = false; } } } }The video below is of the RobotC Button Latch in Action!: