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);
}
5 Likes
Sorry I didnt thank you earlier, this helped a ton. Just curious if you could help me figure out how to make another button that would run it in reverse, nothing seems to work for me.
Let see if the following works…
//Replaced toggle with velocity variable
double velocity = 0;
bool buttonLast = false;
void conveyor_control() {
if(master.get_digital(DIGITAL_Y)) {
if(!buttonLast)
{
//If not going forward
if(velocity != 127)
{
//Go forward
velocity = 127;
}
else {
//Else stop
velocity = 0;
}
buttonLast = true;
}
} else if(master.get_digital(DIGITAL_X)) {
if(!buttonLast)
{
//If not going reverse
if(velocity != -127)
{
//Go reverse
velocity = -127;
}
else {
//Else stop
velocity = 0;
}
buttonLast = true;
}
}
//when button is released, let go of latch.
else {
buttonLast = false;
}
set_conveyor(velocity);
}
3 Likes
It worked, i really appreciate all your help
1 Like