カテゴリー
Raspberry Pi 電子工作

備忘録 1.3inch OLED HAT

 これは自分のためのメモです。
 この備忘録を見られて真似されても結構ですが、動作の保証は出来かねます。
 また、真似られたことで不測の不具合が発生しましても、私は一切の責任を負いません。


Waveshafe 1.3inch OLED HAT wiki

wikiに倣い、config.txtを修正する。

# Uncomment some or all of these to enable the optional hardware interfaces
dtparam=i2c_arm=on ← コメントアウトを外す
#dtparam=i2s=on
dtparam=spi=on ← コメントアウトを外す

check whether SPI is occupied. If the terminal outputs /dev/spidev0.1 and /dev/spidev0.1, SPI is not occupied.

$ls /dev/spi*


ライブラリーのインストール
BMC2835関係のみ必要。(wikiにあるWiringPiは不要)
ここで最新を確認する。

2023年9月22日時点で バージョン1.73

#Open the Raspberry Pi terminal and run the following command
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.73.tar.gz
tar zxvf bcm2835-1.73.tar.gz
cd bcm2835-1.73/
sudo ./configure && sudo make && sudo make check && sudo make install
# For more information, please refer to the official website: http://www.airspayce.com/mikem/bcm2835/

Pythonのライブラリーをpipインストールする
#python3
sudo apt-get update
sudo apt-get install python3-pip 
sudo pip3 install RPi.GPIO
sudo apt-get install python3-smbus
sudo pip3 install spidev

waveshare提供のサンプルプログラムをダウンロード


sudo apt-get install p7zip-full
wget https://files.waveshare.com/upload/5/53/1.3inch-OLED-HAT-Code.7z
7zr x 1.3inch-OLED-HAT-Code.7z -r -o.
sudo chmod 777 -R  RaspberryPi

サンプルプログラムの実行
cd RaspberryPi/python3/
sudo python3 main.py
sudo python3 key_demo.py

IPアドレスとCPU温度を表示させる。

sudo pip3 install ipget

test.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import SH1106
import time
import config
import traceback
import ipget

from PIL import Image,ImageDraw,ImageFont

tempfile='/sys/class/thermal/thermal_zone0/temp'

def getTemp():
    with open(tempfile, 'r') as f:
        rdata = f.readline()
        t = float(rdata)/ 1000.0
    return  t

target_ip = ipget.ipget()
print(target_ip.ipaddr("wlan0"))
wlan_ip = target_ip.ipaddr("wlan0")

t = getTemp()
cputemp = 'cputemp=%.2f C' % (t)


try:
    disp = SH1106.SH1106()

    print("\r\r1.3inch OLED")
    # Initialize library.
    disp.Init()
    # Clear display.
    disp.clear()

    # Create blank image for drawing.
    image1 = Image.new('1', (disp.width, disp.height), "WHITE")
    draw = ImageDraw.Draw(image1)
    font = ImageFont.truetype('Font.ttf', 20)
    font10 = ImageFont.truetype('Font.ttf',13)
#    print ("***draw line")
#    draw.line([(0,0),(127,0)], fill = 0)
#    draw.line([(0,0),(0,63)], fill = 0)
#    draw.line([(0,63),(127,63)], fill = 0)
#    draw.line([(127,0),(127,63)], fill = 0)
#    print ("***draw rectangle")

    print ("***draw text")
#    draw.text((30,0), 'Waveshare ', font = font10, fill = 0)
    draw.text((0,0), wlan_ip, font = font10, fill = 0)
    draw.text((0,20), cputemp, font = font10, fill = 0)
#    draw.text((28,20), u'あいうえ ', font = font, fill = 0)

    # image1=image1.rotate(180)
    disp.ShowImage(disp.getbuffer(image1))
    time.sleep(2)

    print ("***draw image")
#    Himage2 = Image.new('1', (disp.width, disp.height), 255)  # 255: clear the frame
#    bmp = Image.open('pic.bmp')
#    Himage2.paste(bmp, (0,5))
#    # Himage2=Himage2.rotate(180)
#    disp.ShowImage(disp.getbuffer(Himage2))

except IOError as e:
    print(e)

except KeyboardInterrupt:
    print("ctrl + c:")
    epdconfig.module_exit()
    exit()

1分毎にに自動更新で表示するようにcrontab -eで編集する

@reboot sleep 20 ; sudo /usr/bin/touch /tmp/amedas ; sudo /usr/bin/chmod 660 /tmp/amedas ;
 cd /home/pi ; /usr/bin/sudo /usr/bin/python3 amedas.py
@reboot sleep 30 ; cd /home/pi/RaspberryPi/python3 ; /usr/bin/sudo /usr/bin/python3 test.py
*/10 * * * * cd /home/pi ; /usr/bin/sudo /usr/bin/python3 amedas.py
*/1 * * * * cd /home/pi/RaspberryPi/python3 ; /usr/bin/sudo /usr/bin/python3 test.py

load averageも表示されてみる

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

import SH1106
import time
import config
import traceback
import ipget

from PIL import Image,ImageDraw,ImageFont

tempfile='/sys/class/thermal/thermal_zone0/temp'
loadfile='/proc/loadavg'

def getTemp():
    with open(tempfile, 'r') as f:
        rdata = f.readline()
        t = float(rdata)/ 1000.0
    return  t

def getCpuload():
    with open(loadfile, 'r') as la:
        rdata = la.readline()
        la = rdata
    return  la

target_ip = ipget.ipget()
wlan_ip = target_ip.ipaddr("wlan0")

t = getTemp()
cputemp = 'cputemp=%.2f C' % (t)

la = getCpuload()
la_list = la.split()
cpuload = 'loadave=' + la_list[0] + ' ' + la_list[1] + ' ' + la_list[2]

try:
    disp = SH1106.SH1106()

    print("\r\r1.3inch OLED")
    # Initialize library.
    disp.Init()
    # Clear display.
    disp.clear()

    # Create blank image for drawing.
    image1 = Image.new('1', (disp.width, disp.height), "WHITE")
    draw = ImageDraw.Draw(image1)
    font = ImageFont.truetype('Font.ttf', 20)
    font10 = ImageFont.truetype('Font.ttf',10)

    print ("***draw text")
    draw.text((0,0), wlan_ip, font = font10, fill = 0)
    draw.text((0,15), cputemp, font = font10, fill = 0)
    draw.text((0,30), cpuload, font = font10, fill = 0)

    disp.ShowImage(disp.getbuffer(image1))
    time.sleep(2)


except IOError as e:
    print(e)

except KeyboardInterrupt:
    print("ctrl + c:")
    epdconfig.module_exit()
    exit()

何故かハマり、先人のお知恵で解決

sudo apt-get install libatlas3-base

アメダスの津地域情報を採取する。
名張では気温情報が無くてハマった。

$sudo touch /var/log/amedas
$sudo chmod 666 /var/log/amedas
 

$ cat amedas.py
#!/usr/bin/env python3
import sys
import requests

from datetime import datetime, timedelta


def get_code(name, name_type='enName'):
    area = requests.get("https://www.jma.go.jp/bosai/amedas/const/amedastable.json").json()
    for code in area:
        if area[code][name_type] == name:
            return code
    else:
        return None


def get_json(datetime_str, code):
    return requests.get(f"https://www.jma.go.jp/bosai/amedas/data/map/{datetime_str}.json").json()[code]


def get_data(code, datetime_str=None):
    if not datetime_str:
        datetime_str = datetime.now().strftime('%Y%m%d%H0000')
        try:
            data = get_json(datetime_str, code)
        except Exception:
            # try to get previous data
            datetime_str = (datetime.now() - timedelta(hours=1)).strftime('%Y%m%d%H0000')
            data = get_json(datetime_str, code)
    else:
        data = get_json(datetime_str, code)
    return data


if __name__ == '__main__':
    try:
        conf = {'area': 'Tsu', 'log': '/tmp/amedas'}
        if len(sys.argv) > 1:
            with open(sys.argv[1]) as f:
                for line in f.readlines():
                    key_value = line.rstrip().split('#')[0].split('=')
                    if len(key_value) != 2:
                        continue
                    conf[key_value[0]] = key_value[1]
        code = conf.get('code', get_code(conf['area']))
        print (code)
#        code = 53151
#        print (code)
        data = get_data(code)
        print (data)
        with open(conf['log'], 'w') as f:
            f.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {data['temp'][0]} {data['humidity'][0]}")
    except KeyboardInterrupt:
        pass

 $ cat RaspberryPi/python3/test.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import SH1106
import time
import config
import traceback
import ipget

from PIL import Image,ImageDraw,ImageFont

tempfile='/sys/class/thermal/thermal_zone0/temp'
loadfile='/proc/loadavg'
amedasfile='/tmp/amedas'

def getTemp():
    with open(tempfile, 'r') as f:
        rdata = f.readline()
        t = float(rdata)/ 1000.0
    return  t

def getCpuload():
    with open(loadfile, 'r') as la:
        rdata = la.readline()
        la = rdata
    return  la

def getAmedas():
    with open(amedasfile, 'r') as la:
        rdata = la.readline()
        la = rdata
    return  la

target_ip = ipget.ipget()
wlan_ip = target_ip.ipaddr("wlan0")

t = getTemp()
cputemp = 'cputemp  %.2f C' % (t)

la = getCpuload()
la_list = la.split()
cpuload = 'loadave  ' + la_list[0] + '  ' + la_list[1] + '  ' + la_list[2]

la = getAmedas()
ame_list = la.split()
amedas = 'Mie Tsu  ' + ame_list[2] + 'C  ' + ame_list[3] + '%'

try:
    disp = SH1106.SH1106()

    print("\r\r1.3inch OLED")
    # Initialize library.
    disp.Init()
    # Clear display.
    disp.clear()

    # Create blank image for drawing.
    image1 = Image.new('1', (disp.width, disp.height), "WHITE")
    draw = ImageDraw.Draw(image1)
    font = ImageFont.truetype('Font.ttf', 20)
    font10 = ImageFont.truetype('Font.ttf',10)

    print ("***draw text")
    draw.text((0,0), wlan_ip, font = font10, fill = 0)
    draw.text((0,15), cputemp, font = font10, fill = 0)
    draw.text((0,30), cpuload, font = font10, fill = 0)
    draw.text((0,45), amedas, font = font10, fill = 0)

    disp.ShowImage(disp.getbuffer(image1))
    time.sleep(2)


except IOError as e:
    print(e)

except KeyboardInterrupt:
    print("ctrl + c:")
    epdconfig.module_exit()
    exit()

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です