[Microbit-Python] While loop without sleep
Nicholas H.Tollervey
ntoll at ntoll.org
Thu Jan 19 15:52:06 EST 2017
On 19/01/17 18:14, Matt Hickford wrote:
> Hi. My program reacts to button presses. The documentation gives an
> example of while loop that checks if the button has been pressed,
> reacts, then sleeps between loops
> https://microbit-micropython.readthedocs.io/en/latest/button.html#example
>
> while True:
> sleep(100)
> if button_a.was_pressed():
> act()
>
> Does it matter if I omit the sleep statement? I wrote
>
> while True:
> if button_a.was_pressed():
> act()
>
> It seems to work. My only concern was, might it drain the battery
> because it's looping very fast? Any thoughts?
> -Matt
>
>
> _______________________________________________
> Microbit mailing list
> Microbit at python.org
> https://mail.python.org/mailman/listinfo/microbit
>
The sleep is to debounce the button.
Say your act() function should only be called once per-press of the
button then if the loop is faster than it takes a human to push the
button down and then release it (and, believe me, it is) then you'll get
a number of calls to act() over the duration of the single push/release
interaction. By adding a shortish sleep you avoid this problem.
Does this make sense? More than happy to answer questions.
N.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 455 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/microbit/attachments/20170119/67ea04c8/attachment.sig>
More information about the Microbit
mailing list