Limit Switch Idea

I had a quickness’s question about programming limit switches in Robot Mesh Studio for C++. Is there any way to program two limit switches so that if at least one of them is pressed, it goes to the next action in the autonomous?

Your exact implementation will vary obviously, but, for most people, the key is to use the or operator (||) in an if conditional or to use the not (!) and and (&&) operators in a while loop conditional:

if( switch1Pressed || switch2Pressed ) {
while( !switch1Pressed && !switch2Pressed ) {}

1 Like

There’s a couple ways to interpret this, depending on if you want to do other things while waiting for the switch to be pressed.

If you want to do other things but transition modes when the switch is pressed, a state machine setup might be a good idea:

while(true) {
    //a few states that can be transitioned between
    switch (state) {
        case 0:
        //state 0 code
        case 1:
        //state 1 code
        case 2:
        //state 2 code
        if (switch1.pressing() || switch2.pressing()) state = somethingNot2;
    if (state == moveOnToAnotherGroupOfStates) break;
//some other states altogether follow here, possibly with their own loops

If you didn’t need to transition between states and just need to go linearly from one to the next, it’s somewhat simpler, akin to what Barin wrote:

void subroutine1();
void subroutine2();

void autonomous() {

void subroutine1() {
    while (true) {
        //stuff for this part
        if (switch1.pressing() || switch2.pressing()) return;

If you just want to delay until one of them is pressed, you can do something like the following, where you delay while neither is pressed:

while(!switch1.pressing() && !switch2.pressing()) sleepMs(1);

There are many ways to handle flow control. It’s part of why programming is something a bit like an art, rather than strictly a science.


I don’t know if this is what you were implying doing, but it needs to be only one switch has to be pressed to go to the next function. Both don’t necessarily have to be pressed (either or needs to be pressed). Would this accomplish this task and go to the next autonomous step.

All the conditionals in my snippets allowed for either switch being pressed to continue on:

(switch1.pressing() || switch2.pressing()) //true if either switch is pressed, or both

Is the permissive variant, and its inverse was used with while to delay until one was pressed:

(!switch1.pressing() && !switch2.pressing()) //only true if neither switch is pressed
1 Like

Thanks for the help, it worked first try. I I used it because I connected two limit switches on the plexiglass alignment for my cap stacker so it would have to be as precise.