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,
Long press button
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Long press button
See this doc, notably the Pushbutton class.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
-
- Posts: 55
- Joined: Sat Sep 18, 2021 10:21 pm
Re: Long press button
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,
Thanks,
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Long press button
Try this, which works on my Pico:
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.
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()
To learn about uasyncio, see my tutorial.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
-
- Posts: 55
- Joined: Sat Sep 18, 2021 10:21 pm
Re: Long press button
@pythoncoder I'm getting an error in thonney....
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,
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'
Thanks,
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Long press button
Ah, sorry, you also need to copy primitives/__init__.py.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
-
- Posts: 55
- Joined: Sat Sep 18, 2021 10:21 pm
Re: Long press button
Sorry for the late reply I'm not getting notifications for some reason.... I'll give it a try thank you very much again!