Fail to use on-board button to change the variable


#1

Hi guys,

I try to use the on-board button on the mBot to change the variable, so that the color of LED will change from “red -> blue -> green” and form a loop of “red -> blue -> green”, one step for one press.

However, it seems that the order is not the same as I programmed. Sometimes, it is red -> blue -> green -> blue. Sometimes, there is no blue color. Or, it may stuck at blue, and need to press many times before changing to red. It seems that the variable behave strangely.

May I know how to tackle this problem?
Or any other method that I can use the on-board button to control the variable.

Thank you so much for your help!


#2

hey, adding a “WAIT for 1 second” after every variable+=1 can solve the problem.
Is it because the variable change too rapidly?


#3

Easy one. When you press the button, the variable is increased very quickly and reset to 0 again, probably a hundret times per second. So it’s more or less random where the increase stops when you release the button.

So after you detect that the button is pressed, you should add another loop which waits until the button is released again.


#4

Thank you Andreas, it works! Many thanks!


#5

I’d also add that while you can have multiple mBot Program hat blocks, anything in a forever loop will get dumped in together (and possibly in the wrong order). You can confirm this by going to Arduino mode, and the reason is that the approach taken by the Arduino folks was to hide the low-level stuff and allow the developer to focus on their application by using a setup() method for initialization code and a loop() method for the main body.

It looks like you are essentially creating a state machine, so I might offer that a different way to do that might be:

The program above has the virtue of not requiring any pauses and will reliably catch the button press. It also affords you the opportunity to change the order of execution by merely changing the value of the light variable to get a different sequence of colors.


#6

chuckmcknight, thank you so much! I will try to do that!


#7