Page 1 of 1
Long press button
Posted: Sun Oct 17, 2021 4:51 am
by soggycashew
Is there a way to detect a long press on a button? For example, lets say I have one button and two LEDs long press turns on the second led but short press turns on the first LED.... If so how can I do it?
Thanks,
Re: Long press button
Posted: Sun Oct 17, 2021 7:30 am
by pythoncoder
See
this doc, notably the Pushbutton class.
Re: Long press button
Posted: Sun Oct 17, 2021 8:35 pm
by soggycashew
Peter, I read that github page and it is very confusing to me since im new to coding and python in general. Can you give me an example for a button single press then long press so I can test it on my breadboard?
Thanks,
Re: Long press button
Posted: Mon Oct 18, 2021 2:18 pm
by pythoncoder
Try this, which works on my Pico:
Code: Select all
from machine import Pin
from primitives.pushbutton import Pushbutton
import uasyncio as asyncio
led = Pin(25, Pin.OUT) # On board LED
pin = Pin(0, Pin.IN, pull=Pin.PULL_UP) # Pushbutton
def toggle():
print("Press")
led(not led())
def report():
print("Long press")
def test():
pb = Pushbutton(pin)
pb.press_func(toggle, ()) # Callback on button press
pb.long_func(report, ()) # Callback on long press
while True:
await asyncio.sleep(1)
print(pin()) # Print current pin state
try:
asyncio.run(test())
finally:
asyncio.new_event_loop()
You will need to go to
https://github.com/peterhinch/micropyth ... /master/v3 and copy the primitives directory with (at least) pushbutton.py and delay_ms.py to your board, keeping the directory structure. Link GPIO 0 to gnd with a pushbutton. You can just copy the whole directory: it takes a minute or so.
To learn about uasyncio, see
my tutorial.
Re: Long press button
Posted: Mon Oct 18, 2021 11:29 pm
by soggycashew
@pythoncoder I'm getting an error in thonney....
Code: Select all
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "primitives/pushbutton.py", line 8, in <module>
ImportError: no module named 'primitives.launch'
I looked for a file named launch in the primitives folder on GitHub and there isn't one? On my Pico I created a directory called primitives and added the two files you specified and tried to run the code you gave in the thread. Is there other files I'm needing?
Thanks,
Re: Long press button
Posted: Tue Oct 19, 2021 8:52 am
by pythoncoder
Ah, sorry, you also need to copy primitives/__init__.py.
Re: Long press button
Posted: Wed Oct 20, 2021 12:08 am
by soggycashew
Sorry for the late reply I'm not getting notifications for some reason.... I'll give it a try thank you very much again!