Created
December 13, 2021 05:33
-
-
Save willcharlton/0b7a710fce6b7757d73c18400ebfdbf2 to your computer and use it in GitHub Desktop.
Micropython Essentials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Self-contained GPIO monitor that implements a notify on push and for how long button was pushed. | |
The purpose of Pinny is to provide a drop-in monitoring solution for monitoring an individual GPIO | |
pin on a system running micropython. | |
The basic way it functions is by using a `deque()` object that it appends integer values to which | |
signify that the button (GPIO Pin) was triggered and for how long (seconds). You can check the | |
length of the queue or implement other means of notifying your application of GPIO activity. | |
Usage: | |
>>> open('boot.py').read() | |
import _craft | |
config = _craft.load_config( | |
{ | |
'craft_deps': { | |
'pinny': 'https://gist.githubusercontent.com/willcharlton/.../raw/.../pinny.py' | |
} | |
} | |
) | |
_craft.install( | |
config=config, | |
reset_on_change=False, | |
) | |
>>> open('main.py').read() | |
import utime | |
from pinny import Pinny | |
user_button = Pinny() | |
while True: | |
if len(user_button.qout) > 0: | |
print(f'button pressed for {user_button.qout.popleft()} seconds') | |
utime.sleep(1) | |
""" | |
import utime | |
import _thread | |
import machine | |
import ulogging as logging | |
from collections import deque | |
class Pinny(object): | |
baton = _thread.allocate_lock() | |
qout = deque((), 1000) | |
def __init__( | |
self, | |
pin=21, | |
direction=machine.Pin.IN, | |
pull=machine.Pin.PULL_UP, | |
trigger=machine.Pin.IRQ_FALLING, | |
callback=None | |
): | |
def this_callback(pin): | |
utime.sleep_us(500) | |
if not pin.value(): | |
if Pinny.baton.locked(): | |
return | |
Pinny.baton.acquire() | |
start_time = utime.time() | |
while not pin.value(): | |
utime.sleep_us(500) | |
now = utime.time() | |
print(f'button press started at: {start_time}, done at: {now} ({now-start_time})') | |
self.qout.append(utime.time() - start_time) | |
Pinny.baton.release() | |
self.button = machine.Pin(pin, direction, pull) | |
utime.sleep_ms(250) | |
self.button.irq( | |
trigger=trigger, | |
handler=callback or this_callback | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment