Raspberry PiでAdafruit製LCD(カラーバックライト+ボタン付きシールド)を利用する

Raspberry PiでAdafruit RGB Negative 16×2 LCD+Keypad Kit for Raspberry Pi – を使ったプログラムをAdafruitの公式ライブラリを使い書いてみました。

シールドの組立、ライブラリのインストールや使い方は公式の方をご覧ください。

下記のソースコードはRasbperry Piの時間とインターフェイス毎のIPアドレスをLCDに表示します。

インターフェイス毎のローカルIPアドレスを取得するために”netifaces”ライブラリを使用しております。
$ apt-get install python-netifaces

/LCDディレクトリを作成し公式ライブラリを入れておきます。
$ sudo mkdir /LCD

$ sudo vi /LCD/MENU_LCD.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python
from netifaces import interfaces, ifaddresses, AF_INET
 
from time import sleep
from Adafruit_I2C import Adafruit_I2C
from Adafruit_MCP230xx import Adafruit_MCP230XX
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
 
from IPaddr_LCD import IPaddr_LCD
from DateTime_LCD import DateTime_LCD
 
import smbus
 
lcd = Adafruit_CharLCDPlate(busnum = 1)
 
class MENU_LCD():
    def get_const_list(self):
        const_list   = []
 
        ip   = IPaddr_LCD()
        time = DateTime_LCD()
 
        const_list.append(ip)
        const_list.append(time)
 
        return const_list
 
    def print_progress(self, sleep_time, message):
        lcd.clear()
        lcd.message(message)
        sleep(sleep_time)
        self.print_lcd()
 
    def print_lcd(self):
        pointer_id = 0
        push_flag  = 0
 
        lcd.clear()
        lcd.message("Please Push\nRite/Left Button")
 
        const_list = self.get_const_list()
        const_list_size = len(const_list) - 1
 
        while 1:
            if (lcd.buttonPressed(lcd.RIGHT) or lcd.buttonPressed(lcd.LEFT)):
                if (lcd.buttonPressed(lcd.RIGHT)):
                    if (pointer_id < const_list_size):
                        pointer_id += 1
                    else:
                        pointer_id = 0
 
                if (lcd.buttonPressed(lcd.LEFT)):
                    if (pointer_id > 0):
                        pointer_id -= 1
                    else:
                        pointer_id = const_list_size
 
                push_flag  = 1
                const_list[pointer_id].title()
 
            if (push_flag > 0 and lcd.buttonPressed(lcd.SELECT)):
                const_list[pointer_id].print_lcd()
                break
 
            if (push_flag > 0 and lcd.buttonPressed(lcd.UP)):
                break
 
            if (push_flag > 0 and lcd.buttonPressed(lcd.DOWN)):
                break
 
            sleep(.2)
        return self.print_progress(1, "Reinitializeing\nPlease wate....")
 
if __name__ == '__main__':
    try:
        menu = MENU_LCD()
        menu.print_progress(3, "Initializeing\nPlease wate....")
        menu.print_lcd()
    except KeyboardInterrupt:
        print("Exit\n")

$ sudo vi /LCD/DateTime_LCD.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
import datetime
import locale
 
from time import sleep
from Adafruit_I2C import Adafruit_I2C
from Adafruit_MCP230xx import Adafruit_MCP230XX
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
 
import smbus
 
lcd = Adafruit_CharLCDPlate(busnum = 1)
 
class DateTime_LCD():
    def title(self):
        lcd.clear()
        lcd.message("Raspberry Pi\nDate Time")
        return
 
    def print_lcd(self):
 
        while 1:
            d = datetime.datetime.today()
            time = d.strftime("Date %Y/%m/%d\nTime  %H:%M:%S")
 
            lcd.clear()
            lcd.message(time)
 
            if (lcd.buttonPressed(lcd.RIGHT)):
                break
 
            if (lcd.buttonPressed(lcd.LEFT)):
                break
 
            sleep(.2)
        return
 
 
if __name__ == '__main__':
    try:
        time = DateTime_LCD()
        time.print_lcd()
    except KeyboardInterrupt:
        print("Exit\n")

$ sudo vi /LCD/IPaddr_LCD.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
from netifaces import interfaces, ifaddresses, AF_INET
 
from time import sleep
from Adafruit_I2C import Adafruit_I2C
from Adafruit_MCP230xx import Adafruit_MCP230XX
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
 
import smbus
 
lcd = Adafruit_CharLCDPlate(busnum = 1)
 
class IPaddr_LCD():
    def title(self):
        lcd.clear()
        lcd.message("Raspberry Pi\nIP Address")
        return
 
    def get_ip_list(self):
        ipaddr_list   = []
        for ifaceName in interfaces():
            nic_ip_list = []
            addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
            nic = '%s' % (ifaceName)
            ip  = '%s' % (', '.join(addresses))
            nic_ip_list.append(nic)
            nic_ip_list.append(ip)
            ipaddr_list.append(nic_ip_list)
        return ipaddr_list
 
    def print_lcd(self):
        pointer_id = 0
 
        lcd.clear()
        lcd.message("Please Push\nUp/Down Button")
 
        while 1:
            if (lcd.buttonPressed(lcd.UP) or lcd.buttonPressed(lcd.DOWN)):
                ipaddr_list = self.get_ip_list()
                ipaddr_list_size = len(ipaddr_list) - 1
 
                if (lcd.buttonPressed(lcd.UP)):
                    if (pointer_id < ipaddr_list_size):
                        pointer_id += 1
                    else:
                        pointer_id = 0
 
                if (lcd.buttonPressed(lcd.DOWN)):
                    if (pointer_id > 0):
                        pointer_id -= 1
                    else:
                        pointer_id = ipaddr_list_size
 
                lcd.clear()
                lcd.message(ipaddr_list[pointer_id][0] + "\n" + ipaddr_list[pointer_id][1])
 
            if (lcd.buttonPressed(lcd.RIGHT)):
                break
 
            if (lcd.buttonPressed(lcd.LEFT)):
                break
 
            sleep(.2)
        return
 
if __name__ == '__main__':
    try:
        ip = IPaddr_LCD()
        ip.print_lcd()
    except KeyboardInterrupt:
        print("Exit\n")

コマンド用の実行ファイルを作成しておきます
$ sudo vi /LCD/LCD_PRINTER

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
from MENU_LCD import MENU_LCD
 
if __name__ == '__main__':
    try:
        menu = MENU_LCD()
        menu.print_progress(3, "Initializeing\nPlease wate....")
        menu.print_lcd()
    except KeyboardInterrupt:
        print("Exit\n")

実行権限を与えどこからでもパスが通るように”/usr/bin/”の中にシンボリックを貼っておきます。
$ sudo chmod 700 /LCD/LCD_PRINTER
$ sudo ln -s /LCD/LCD_PRINTER /usr/bin/LCD_PRINTER

せっかくなので起動スクリプトも書いてみました。
$ sudo mkdir /LCD/init.d/
$ sudo vi /LCD/init.d/lcd_printer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/sh
### BEGIN INIT INFO
# Provides:          LCD_PRINTER
# chkconfig:         2345 91 91
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       LCD_PRINTER daemon script.
### END INIT INFO
 
. /lib/lsb/init-functions
 
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/LCD_PRINTER
DAEMON_NAME=`basename $DAEMON`
PIDFILE="/var/run/lcd_printer.pid"
 
set -e
 
start() {
  log_daemon_msg "Starting $DAEMON_NAME"
  if ! start-stop-daemon --stop --quiet --pidfile ${PIDFILE} --signal 0; then
    start-stop-daemon --start --pidfile ${PIDFILE} --make-pidfile --quiet --background --exec ${DAEMON}
    log_end_msg $?
  else
    echo -n " already running."
    log_end_msg 1
  fi
}
 
stop() {
  log_daemon_msg "Stopping $DAEMON_NAME"
  start-stop-daemon --stop --pidfile ${PIDFILE}
  log_end_msg $?
}
 
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  status)
    status_of_proc -p $PIDFILE $DAEMON $DAEMON_NAME && exit 0 || exit $?
    ;;
  *)
    echo $"Usage: $DAEMONNAME {start|stop|restart|status}" >&2
    exit 1
    ;;
esac
exit 0

実行権限を与え、起動スクリプトとして”/etc/init.d/”の中にシンボリックを貼っておきます。
$ sudo chmod 755 /LCD/init.d/lcd_printer
$ sudo ln -s /LCD/init.d/lcd_printer /etc/init.d/lcd_printer

起動するか確認してみます。
$ sudo service lcd_printer start

自動起動するように設定します。
$ sudo update-rc.d lcd_printer defaults

自動起動するか確認します。完全に電源を落とすためrebootではなくシャットダウンして電源を入れます。
$ sudo shutdown -h now

余談ですがRedHat系はchkconfigで設定するのですがDebian系は違うのですね・・・勉強になりました。

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(Spamcheck Enabled)

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)