view lameboy.py @ 14:8239a9ade11d draft default tip

Add a license
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Fri, 23 Feb 2018 12:07:23 +0100
parents 464aa1a9f0f8
children
line wrap: on
line source

import framebuf
import time
import busio
import digitalio
import board


class Display:
    width = 84
    height = 48

    def __init__(self, spi, dc, rst, cs):
        self._spi = spi
        self._cs = cs
        self._rst = rst
        self._dc = dc
        self._fn = 0x20
        self._buffer = bytearray(504)
        self.fb = framebuf.FrameBuffer(self._buffer, 84, 48,
                                       framebuf.MONO_VLSB)
        self.reset()

    def _command(self, command):
        self._dc.value = False
        self._cs.value = False
        self._spi.write(command)
        self._cs.value = True
        self._dc.value = True

    def reset(self):
        self._rst.value = False
        time.sleep(0.1)
        self._rst.value = True
        time.sleep(0.1)
        self.contrast()
        self.inverse(0)

    def active(self, val):
        if val:
            self._fn &= ~0x04
        else:
            self._fn |= 0x04
        self._command(bytes((self._fn,)))

    def inverse(self, val):
        self._command(b'\x0d' if val else b'\x0c')

    def contrast(self, val=63, bias=20, temp=6):
        if not (0 <= val <= 127 and 16 <= bias <= 23 and 4 <= temp <= 7):
            raise ValueError()
        self._command(bytes((self._fn | 1, temp, bias, 0x80 | val, self._fn)))

    def update(self):
        self._dc.value = False
        self._cs.value = False
        self._spi.write(b'\x40\x80')
        self._dc.value = True
        self._spi.write(self._buffer)
        self._cs.value = True


class Backlight:
    def __init__(self, i2c, address=0x0d):
        self._i2c = i2c
        self._address = address

    def color(self, r, g, b):
        data = bytearray((0x6e, r, g, b))
        self._i2c.writeto(self._address, data)


class Buttons:
    UP = 0x80
    LEFT = 0x40
    DOWN = 0x20
    RIGHT = 0x10
    A = 0x08
    B = 0x04
    C = 0x01
    _byte = bytearray(1)

    def __init__(self, i2c, address=0x38):
        self._i2c = i2c
        self._address = address

    def get_pressed(self):
        try:
            self._i2c.readfrom_into(self._address, self._byte)
        except OSError:
            self._byte[0] = 0xff
        return self._byte[0] ^ 0xff


i2c = busio.I2C(sda=board.SDA, scl=board.SCL)
i2c.try_lock()
backlight = Backlight(i2c)
buttons = Buttons(i2c)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
spi.try_lock()
spi.configure(baudrate=10000000)
_dc = digitalio.DigitalInOut(board.GPIO2)
_dc.switch_to_output(value=True)
_rst = digitalio.DigitalInOut(board.GPIO0)
_rst.switch_to_output(value=True)
_cs = digitalio.DigitalInOut(board.GPIO15)
_cs.switch_to_output(value=True)
display = Display(spi, _dc, _rst, _cs)