Quote:
Originally Posted by RoastBeefer
Hello, we have a conveyor belt powered by a motor on our bot. We want to press a button and make it run until we press the same button again. We cannot figure out how to do this. Here is what we currently have for our code:
Code:
//Conveyor Belt
boolean belt = false;
conveyorMotor.set(0);
if(belt == false){
if(stick.getRawButton(3)){
belt = true;
conveyorMotor.set(1);
}
else if(belt == true){
if(stick.getRawButton(3)){
belt = false;
conveyorMotor.set(0);
}
}
Currently this only turns on the belt while pressed and stops as soon as we let go. I feel like we're taking the totally wrong approach to this. Please help
|
Are you reinitializing the belt = false every time you execute the following code? If so, every time you run the above code, belt will get set to false and only become true if the button is currently pressed.
Also, to implement a toggling routine in code that takes input from a human, you need a way to slow it down or track previous states. For example, if a toggle function runs once every 10ms, a human pressing a button for 1/2 a second will cause the code to toggle 50 times.
There are two ways to overcome this: timers (only allowing the code to toggle once every ___ ms), or by only toggling the output on button transitions (such as from a not pressed state to a pressed state). Here's a real quick piece of [untested] code that works off the latter principle:
Code:
// Run this only once to initialize the variables
boolean beltStatus = false;
boolean previousButton = false;
boolean currentButton = false;
Code:
// Run the following code continuously
previousButton = currentButton
currentButton = stick.getRawButton(3);
if (currentButton && !previousButton)
{
beltStatus = beltStatus ? false : true;
}
conveyorMotor.set((double)(beltStatus ? 1 : 0));
This code works by only looking for button transitions (e.g. last time the code ran the button was not pressed and this time it is pressed). It then toggles the state of beltStatus if this transition is detected. After that, the motor output is set by using another ternary operation to typecast the boolean belt state as a double.