0

I made this short code for a school project using a Microbit computer, however, when I press the a button when the count is 1, the count jumps to 16 and I can't figure out why.

count = (1)

while True:
    gesture = accelerometer.current_gesture()
    display.show(count)
    if button_a.is_pressed():
        count *= (2)
    if button_b.is_pressed():
        count += (1)
    if gesture == "shake":
        count = (1)

any help would be greatly appreciated!

Lucas R
  • 11
  • Perhaps the program goes round 4 times whilst the button is pressed. What about the other button. What happens then? – quamrana Nov 19 '19 at 20:45
  • Could it be that you're holding the button too long? It may seem like a short time for you, but several milliseconds are enough for hundreds of thousands of cpu calculations. You can add a pause to your program if you suspect this is happening. a `time.sleep(1)` at the end of your `while True` loop to pause for 1 second. This may not be ideal for the final version, **but** it will help you figure out what's going on *right now*. – SyntaxVoid Nov 19 '19 at 20:47
  • 1
    Maybe it is because the program runs so fast, that it thinks you pressed it multiple times. Try to add a `time.sleep(1)` at the end of the loop. you need to `import time` – Uli Sotschok Nov 19 '19 at 20:47
  • 1
    Physical buttons usually need a "de-bouncing" mechanism, either in the hardware or the software so that a single human press doesn't trigger the mechanism multiple times. – mgrollins Nov 19 '19 at 20:50
  • As some colleagues above suggest, maybe the key press is repeating. Is it possible in your environment to detect a key release? if so, you may want to work that into your logic. Also, there's no need to put your single integers inside a tuple. It doesn't hurt, but it doesn't accomplish anything either. – GaryMBloom Nov 19 '19 at 20:52

2 Answers2

2

If count does not always increase by 16 on each click, you are likely dealing with button de-bouncing issue. Like others have suggested, you could use sleep(1) to check whether that is case or not, but for more practical solution you could do the following:

# detect click of button
if button.is_pressed():
    count += 1
    # do nothing while button remains clicked for the duration
    while button.is_pressed():
        pass
Ach113
  • 1,775
  • 3
  • 18
  • 40
1

As other contributors commented, more than one button push is being detected for a single button push.

With Micropython, to avoid repeated button presses being detected for a single button press use the code:

if button_a.was_pressed():

instead of:

if button_a.is_pressed():
Oppy
  • 2,662
  • 16
  • 22