Button toggle code makes rest of bot not work

I’ve been trying to program a button toggle for our conveyor so we can press it and it will run until pressed again. I got it to work, but the rest of the robot will not move when trying to use the joysticks or other buttons. I figured out that removing the while(true) in the toggle code fixes this but makes the button no longer a toggle and i have to hold it down. Any help would be appreciated

You should only have one while(true). That code will never exit so it gets locked into the inner while.

Use If statements instead.

To take advantage of the latch toggle it needs to be declared outside (above) of the conveyor_control() function. Every time you call conveyor_control() it creates a new instance of the buttonLast and toggle so it doesn’t remember the previous state.

Edit: Added sample code

bool toggle = false;
bool buttonLast = false;

void conveyor_control() {
	//If button is being pressed
	if(master.get_digital(DIGITAL_Y)) {
		//If this is the first time the button press is detected - otherwise skip
		if(!buttonLast)
		{
			toggle = !toggle;
			buttonLast = true;
		}
	}
	//when button is released, let go of latch.
	else {
		buttonLast = false;
	}
		
	if(toggle) 
		set_conveyor(127);
	else 
		set_conveyor(0);
}
4 Likes