...
...
...
...
...
...
Created by Franck Albinet with source available here. Also presented by NSRC at APRICOT 2018.
Button: Detecting Pysense board button pressure
...
Code Block | ||||
---|---|---|---|---|
| ||||
# we import the Pin `class` from machine Pycom modules from machine import Pin # then we create a `pin` object button = Pin("P14", mode=Pin.IN, pull=Pin.PULL_UP) |
You notice that to create a Pin
object we need to specify three arguments:
- pin's
id
"P14"
- see Pysense board manual "pysense-pinout-comp.pdf" in/labs/references
; - pin's mode
Pin.IN
specifying that this is an input - pull method
Pin.PULL_UP
specifying we want a pull-up resistor. Loosely speaking, a pull-up or pull-down resistor will ensure that the pin is in either a high or low state, while also using a low amount of current and as a result prevents unknown state of the input. You can consult this blog post for further information https://learn.sparkfun.com/tutorials/pull-up-resistors.
Now that we have a button object, let's read repeatedly the state of the input. In our case when not pressed the button's value button()
should be 1 and 0 when pressed (pull-up resistor).
...
Code Block | ||||
---|---|---|---|---|
| ||||
class Button: def __init__(self, id): self.pressed = False self.btn = Pin(id, mode=Pin.IN, pull=Pin.PULL_UP) |
__init___
is a special method called at instance/object creation (when we call Button('button_id')
actually). We initialize here button's state and create it.
Code Block | ||||
---|---|---|---|---|
| ||||
def on(self): self.btn.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING, self._handler) def off(self): self.btn.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING, None) |
...