Skip to content

button

Button Utilities.

Including debouncing of the button.

Classes:

Name Description
Button

Button class.

Functions:

Name Description
test_button

Test for the Button class.

Button

Button(button_pin: int)

Button class.

Parameters:

Name Type Description Default
button_pin int

The pin the button of the encoder is connected to.

required

Methods:

Name Description
button_changed

Indicates if the button value changed since the last call to this method.

get_button

Get the button value.

Source code in src/aalec/button.py
18
19
20
21
22
23
24
25
26
27
28
def __init__(self, button_pin: int):
    self._pin = machine.Pin(button_pin, machine.Pin.IN, machine.Pin.PULL_UP)
    self._timer = machine.Timer(-1)
    self._timer.init(
        mode=machine.Timer.PERIODIC,
        period=constants.SAMPLE_PERIOD,
        callback=self._debounce_isr,
    )
    self._state: int = 0
    self._value: int = 0
    self._old_value: int = 0

button_changed

button_changed() -> bool

Indicates if the button value changed since the last call to this method.

Returns:

Name Type Description
bool bool

True if the value has changed since the last call. False otherwise.

Source code in src/aalec/button.py
38
39
40
41
42
43
44
45
46
47
48
49
def button_changed(self) -> bool:
    """Indicates if the button value changed since the last call to this method.

    Returns:
        bool: `True` if the value has changed since the last call. `False` otherwise.
    """
    rc = False
    current_value = self.get_button()
    if self._old_value != current_value:
        rc = True
        self._old_value = current_value
    return rc

get_button

get_button() -> int

Get the button value.

Returns:

Name Type Description
int int

Value of the button. Button pressed: 1. Button released: 0.

Source code in src/aalec/button.py
30
31
32
33
34
35
36
def get_button(self) -> int:
    """Get the button value.

    Returns:
        int: Value of the button. Button pressed: `1`. Button released: `0`.
    """
    return self._value

test_button

test_button() -> None

Test for the Button class.

Source code in src/aalec/button.py
65
66
67
68
69
70
71
72
73
def test_button() -> None:
    """Test for the Button class."""
    b = Button(constants.PIN_BUTTON)

    print(f"Button value: {b.get_button()}", end="\r")

    while True:
        if b.button_changed():
            print(f"Button value: {b.get_button()}", end="\r")