My students are working on a simple challenge building a spinning sign that turns on when the bumper switch is pressed and then turns off when the same switch is pressed again. The code some of them are using is below. It does not work smoothly but is erratic. What would be the correct block code?
You need the second “if” statement to have a “not” in front of the “bumper pressed” so it looks like this: if not bumper pressed- stop motor6. Because right now it is just changing between the two “if” statements because they are both true which is why you get the erratic motor behavior.
Or more concisely, you could use an “if-else” block – If the bumper is pressed, spin the motor forward; else, stop the motor.
EDIT: Actually, that would cause the motor to spin while the bumper is pressed which I now see is not the behavior you described.
What you need to make this work is some kind of “hysteresis” – that is, each time the button is pressed, in order to know what action to take you need to know whether or not the motor is currently spinning.
I’ll leave the precise implementation as an exercise for the reader for now, but as a hint, I think the “when bumper pressed” hat block would make that a lot easier.
Seeing you are the Mentor, I will just give you the code, but please do not just give the code to the students. Guide them. Replace the R Up with Bumper 2, and you can tweak the wait 1 second to be lower if you want, this is just a starting point to help you out.
Awesome!! Thanks so much
What is “Driving”?
found it…It’s a variable
The problem with the above doce is that, unless you press the sensor for less than a split second, it will keep toggling the options
Thanks the help. The code is not working.
Here is the code I added.
For the wait block put a wait until block then in that put a “not bumper pressed”
I like doing the latch demos for new teams.
Inside the Forever loop the code is being evaluated numerous times each second. If you hold down the bumper switch it will change the motor state back and forth in each loop (on / off / on / off every second).
If you add a latch it only allows the MotorRun variable to switch one time and it will not switch again until you let go of the bumper (un-latch) and press it again.
That worked perfect. I will study it to better understand the logic. Thanks much!
I used a wait command, you might have not saw it or I overlooked something, can you tell me what would cause that, (that came off a bit mad, I am competing in two weeks I genually want to know so I can fix it in my code)
Sorry, I didn’t see the wait. Regardless, with a wait, at the worst, you need to push the button for a second to register. Also, anything else in the loop will only update every second. Instead, I would recommend a latch, like the code posted above by @Hudsonville_Robotics . This will let you loop frequently, and it will regestor a button push when it happens.
I see now, thanks for clarifying.