【進撃の東さん】第6回：電子ペーパーで遊んでみましょう

# 概要

Raspberry Pi PicoとPico e-Paper 5.65という７色電子ペーパーを使って画像を描画する方法について解説しています。

https://youtu.be/CNqX-YLv6P0

# GIMPで使ったカスタムパレット

```text:pallete.txt
#ffffff
#000000
#ff0000
#ffa500
#0000ff
#00ff00
#ffff00
```

# ソースコード

#### PNGをCSVに変換する

```python:create_csv.py
"""GIMPで作ったPNGをCSVに変換する"""

# ファイル名（拡張子を除く）を入力する
file_name = ''

from PIL import Image
import csv

# 画像を開く
image = Image.open(file_name + '.png')

# 画像の幅と高さを取得
width, height = image.size
print(width, height)

# 各ピクセルの値を取得
pixels = list(image.getdata())

# 2次元リストに変換（行ごとに分割）
pixel_matrix = [pixels[i:i+width] for i in range(0, len(pixels), width)]

# ピクセルデータをCSVに書き込む
csv_file = file_name + '.csv'

with open(csv_file, "w", newline="") as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in pixel_matrix:
        csvwriter.writerow(row)

print(f"CSVファイル '{csv_file}' にデータを保存しました。")

```

#### CSVファイルを電子ペーパーに描画する

```python:epaper.py
# *****************************************************************************
# * | File        :  Pico_ePaper-5.65.py
# * | Author      :   Waveshare team
# * | Function    :   Electronic paper driver
# * | Info        :
# *----------------
# * | This version:   V1.0
# * | Date        :   2021-06-04
# # | Info        :   python demo
# -----------------------------------------------------------------------------
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to  whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

from machine import Pin, SPI
import framebuf
import utime

# Display resolution
EPD_WIDTH       = 600
EPD_HEIGHT      = 448

RST_PIN         = 12
DC_PIN          = 8
CS_PIN          = 9
BUSY_PIN        = 13

class EPD_5in65(framebuf.FrameBuffer):
    def __init__(self):
        self.reset_pin = Pin(RST_PIN, Pin.OUT)
        
        self.busy_pin = Pin(BUSY_PIN, Pin.IN, Pin.PULL_UP)
        self.cs_pin = Pin(CS_PIN, Pin.OUT)
        self.width = EPD_WIDTH
        self.height = EPD_HEIGHT
        
        self.Black = 0x00
        self.White = 0x01
        self.Green = 0x02
        self.Blue = 0x03
        self.Red = 0x04
        self.Yellow = 0x05
        self.Orange = 0x06
        self.Clean = 0x07
        
        
        self.spi = SPI(1)
        self.spi.init(baudrate=4000_000)
        self.dc_pin = Pin(DC_PIN, Pin.OUT)
        

        self.buffer = bytearray(self.height * self.width // 2)
        super().__init__(self.buffer, self.width, self.height, framebuf.GS4_HMSB)
        
        self.EPD_5IN65F_Init()

    def digital_write(self, pin, value):
        pin.value(value)

    def digital_read(self, pin):
        return pin.value()

    def delay_ms(self, delaytime):
        utime.sleep(delaytime / 1000.0)

    def spi_writebyte(self, data):
        self.spi.write(bytearray(data))

    def module_exit(self):
        self.digital_write(self.reset_pin, 0)

    # Hardware reset
    def reset(self):
        self.digital_write(self.reset_pin, 1)
        self.delay_ms(200) 
        self.digital_write(self.reset_pin, 0)
        self.delay_ms(1)
        self.digital_write(self.reset_pin, 1)
        self.delay_ms(200)   

    def send_command(self, command):
        self.digital_write(self.dc_pin, 0)
        self.digital_write(self.cs_pin, 0)
        self.spi_writebyte([command])
        self.digital_write(self.cs_pin, 1)

    def send_data(self, data):
        self.digital_write(self.dc_pin, 1)
        self.digital_write(self.cs_pin, 0)
        self.spi_writebyte([data])
        self.digital_write(self.cs_pin, 1)
        
    def send_data1(self, buf):
        self.digital_write(self.dc_pin, 1)
        self.digital_write(self.cs_pin, 0)
        self.spi.write(bytearray(buf))
        self.digital_write(self.cs_pin, 1)
        
    def BusyHigh(self):
        while(self.digital_read(self.busy_pin) == 0):
            self.delay_ms(1)
            
    def BusyLow(self):
        while(self.digital_read(self.busy_pin) == 1):
            self.delay_ms(1)
        
    def EPD_5IN65F_Init(self):
    
        self.reset();
        self.BusyHigh();
        self.send_command(0x00);
        self.send_data(0xEF);
        self.send_data(0x08);
        self.send_command(0x01);
        self.send_data(0x37);
        self.send_data(0x00);
        self.send_data(0x23);
        self.send_data(0x23);
        self.send_command(0x03);
        self.send_data(0x00);
        self.send_command(0x06);
        self.send_data(0xC7);
        self.send_data(0xC7);
        self.send_data(0x1D);
        self.send_command(0x30);
        self.send_data(0x3C);
        self.send_command(0x41);
        self.send_data(0x00);
        self.send_command(0x50);
        self.send_data(0x37);
        self.send_command(0x60);
        self.send_data(0x22);
        self.send_command(0x61);
        self.send_data(0x02);
        self.send_data(0x58);
        self.send_data(0x01);
        self.send_data(0xC0);
        self.send_command(0xE3);
        self.send_data(0xAA);
        
        self.delay_ms(100);
        self.send_command(0x50);
        self.send_data(0x37);

    def EPD_5IN65F_Clear(self,color):
    
        self.send_command(0x61)   # Set Resolution setting
        self.send_data(0x02)
        self.send_data(0x58)
        self.send_data(0x01)
        self.send_data(0xC0)
        self.send_command(0x10)
        for i in range(0,int(self.width / 2)):
            self.send_data1([(color<<4)|color] * self.height)

        self.send_command(0x04)   # 0x04
        self.BusyHigh()
        self.send_command(0x12)   # 0x12
        self.BusyHigh()
        self.send_command(0x02)   # 0x02
        self.BusyLow()
        self.delay_ms(500)
        
    def EPD_5IN65F_Display(self,image):

        self.send_command(0x61)   # Set Resolution setting
        self.send_data(0x02)
        self.send_data(0x58)
        self.send_data(0x01)
        self.send_data(0xC0)
        self.send_command(0x10)
        
        for i in range(0, int(self.width // 2)):            
            self.send_data1(image[(i*self.height):((i+1)*self.height)])
            
        self.send_command(0x04)   # 0x04
        self.BusyHigh()
        self.send_command(0x12)   # 0x12
        self.BusyHigh()
        self.send_command(0x02)   # 0x02
        self.BusyLow()
        self.delay_ms(200)
    
    def EPD_5IN65F_Display_part(self,image,xstart,ystart,image_width,image_heigh):

        self.send_command(0x61)   # Set Resolution setting
        self.send_data(0x02)
        self.send_data(0x58)
        self.send_data(0x01)
        self.send_data(0xC0)
        self.send_command(0x10)
        for i in range(0, self.height):
            for j in range(0, int(self.width / 2)):
                if((i<(image_heigh+ystart)) & (i>(ystart-1) ) & (j<(image_width+xstart)/2) & (j>(xstart/2 - 1))):
                    self.send_data(image[(j-xstart/2) + (image_width/2*(i-ystart))])
                else:
                    self.send_data(0x11)

        self.send_command(0x04)   # 0x04
        self.BusyHigh()
        self.send_command(0x12)   # 0x12
        self.BusyHigh()
        self.send_command(0x02)   # 0x02
        self.BusyLow()
        self.delay_ms(200)
        

                
    def Sleep(self):
        self.delay_ms(100);
        self.send_command(0x07);
        self.send_data(0xA5);
        self.delay_ms(100);
        self.digital_write(self.reset_pin, 1)


key0 = Pin(15, Pin.IN, Pin.PULL_UP)
key1 = Pin(17, Pin.IN, Pin.PULL_UP)
key2 = Pin(2, Pin.IN, Pin.PULL_UP)

def display_image(csv_file):
    epd = EPD_5in65()
    
    epd.fill(0xff)
    
    with open(csv_file, 'r') as f:
        for y in range(EPD_HEIGHT):
            row = f.readline()
            row = row.split('\n')[0]
            row = row.split(',')
            for x in range(EPD_WIDTH):
                color = int(row[x])
                if color == 0:
                    color = epd.White
                elif color == 1:
                    color = epd.Black
                elif color == 2:
                    color = epd.Red
                elif color == 3:
                    color = epd.Orange
                elif color == 4:
                    color = epd.Blue
                elif color == 5:
                    color = epd.Green
                elif color == 6:
                    color = epd.Yellow
                epd.pixel(x, y, color)
        
    epd.EPD_5IN65F_Display(epd.buffer) 

def clear():
    epd = EPD_5in65()
    epd.EPD_5IN65F_Clear(epd.White)

if __name__=='__main__':
    while True:
        if key0.value() == 0:
            print('key0が押されました。')
            display_image('pokemon.csv')
            utime.sleep(1)
        elif key1.value() == 0:
            print('key1が押されました。')
            utime.sleep(1)      
        elif key2.value() == 0:
            print('key2が押されました。')
            clear()
            utime.sleep(1)                       
```

# 参考

https://www.waveshare.com/wiki/Pico-ePaper-5.65

https://github.com/waveshareteam/Pico_ePaper_Code/tree/main

https://www.gimp.org

https://thonny.org