Raspberry Pi (8) Nokia 5110 LCD 2nd

一年前にNokia 5110 LCDの表示が出来たが、今回はそれをRaspberry Pi に組み込み、されにボタンを追加する。

ボタンは短押し検知すると、LCDのバックライトのon/offで、さらに長押しすると、Raspberry Piシャットダウン機能も持たせる。

GPIOへのスイッチオン・オフ検知回路。

sw1

Pythonプログラム

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import time
import RPi.GPIO as GPIO
import os

# LEDのGPIOピンの番号、センサーのGPIOピンの番号
let_pin = 18
sw1_pin = 16
sleeptime = 1
led_01 = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(sw1_pin, GPIO.IN)
GPIO.setup(let_pin, GPIO.OUT)
GPIO.output(let_pin, GPIO.LOW)
def switch_detected(sw1_pin):
  global led_01
  led_01 = 1 - led_01
  if led_01 == 1:
    # 点灯
    GPIO.output(let_pin, GPIO.HIGH)
  else:
    # 消灯
    GPIO.output(let_pin, GPIO.LOW)

  sw_counter = 0
  while True:
      sw_status = GPIO.input(sw1_pin)
      if sw_status == 0:
          sw_counter = sw_counter + 1
          if sw_counter >= 50:
              print("長押し検知!")
              os.system("sudo shutdown -h now")
              break
      else:
          print("短押し検知")
          break

      time.sleep(0.01)
  time.sleep(sleeptime)

# コールバック登録
GPIO.add_event_detect(sw1_pin, GPIO.FALLING, callback=switch_detected)
try:
  print "ctrl+c  :  if you want to stop app"
  print "App Start"
  while True:
    time.sleep(sleeptime)
except KeyboardInterrupt:
  print "Quit"
finally:
  print "clean up"
  GPIO.cleanup()

これを起動時自動的に作動する必要がある。

参考:

  • https://qiita.com/clses/items/e701c1cb6490751a6040 – ラズパイでシャットダウンボタンを付ける(ついでに起動ボタン)