LoginSignup
1
1

More than 3 years have passed since last update.

gpiozeroのAPIでボタンの長押、短押をシンプルにコーディングする。

Last updated at Posted at 2020-02-23

はじめに

  • Raspberry piのGPIOにタクトボタンを接続し、長押しした時と短押しした時で別の機能を割り当てる方法です。いくつかの方法を試しましたが gpiozero https://gpiozero.readthedocs.io/en/stable/index.html のAPIが使いやすいと思ったので紹介します。

1. インストール方法

私は、Python3用をインストールしました。

2. ボタンの長押、短押サンプル

https://gpiozero.readthedocs.io/en/stable/faq.html#how-do-i-use-button-when-pressed-and-button-when-held-together
上記、FAQのページにサンプルがあります。ほんの少しだけ修正してわかりやすくしてみました。

#!/usr/bin/python3
# coding:utf-8

from gpiozero import Button
from signal import pause

Button.was_held = False

def held(btn):
    btn.was_held = True
    print("button", btn.pin.number, "長押検知")

def released(btn):
    if not btn.was_held:
        print("button", btn.pin.number, "短押検知")
    btn.was_held = False

btn_11 = Button(11)
btn_19 = Button(19)

btn_11.when_held = held
btn_11.when_released = released
btn_19.when_held = held
btn_19.when_released = released

pause()

Buttonクラスにある、when_held(ボタンを押した時間が設定時間を経過した時、指定した関数を実行する)とwhen_released(ボタンをリリースした時=押すのをやめた時、指定した関数を実行する)を使って実現しています。ボタンをリリースした時のイベントは長押、短押両方で検知しますが、リリース時にbtn.was_heldの状態を確認することで「短押検知」を可能にしています。
ボタンに割り当てたい機能毎に関数を作成するか、上記関数内でpin番号毎に処理を割り振れば良いと思います。

3. その他

Mock pins を使えば、Raspberry Piが手元になくてもコードのテストが可能です。
https://gpiozero.readthedocs.io/en/stable/api_pins.html#mock-pins

iPython等を使って動きを確認することができるので便利です。
ちなみに長押はbtn.pin.drive_low()、一旦ボタンの状態を元に戻しbtn.pin.drive_high() 、短押はbtn.pin.drive_low();btn.pin.drive_high()でシミュレートできます。btn.pin.drive_low()が押した状態、btn.pin.drive_high()が放した状態です。

Raspberry PiのGPIOめちゃくちゃ楽しいです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1