|
| 1 | +import ustruct |
| 2 | +import utime |
| 3 | + |
| 4 | + |
| 5 | +class Display(object): |
| 6 | + _BUF = bytearray(4) |
| 7 | + |
| 8 | + width = 320 |
| 9 | + height = 240 |
| 10 | + |
| 11 | + def __init__(self, spi, dc, cs=None, rst=None): |
| 12 | + self.spi = spi |
| 13 | + self.dc = dc |
| 14 | + self.cs = cs or (lambda x: x) |
| 15 | + self.rst = rst or (lambda x: x) |
| 16 | + self.reset() |
| 17 | + |
| 18 | + def reset(self): |
| 19 | + self.rst(0) |
| 20 | + utime.sleep_ms(50) |
| 21 | + self.rst(1) |
| 22 | + utime.sleep_ms(50) |
| 23 | + self.cs(0) |
| 24 | + for command, data in ( |
| 25 | + (b'\xef', b'\x03\x80\x02'), |
| 26 | + (b'\xcf', b'\x00\xc1\x30'), |
| 27 | + (b'\xed', b'\x64\x03\x12\x81'), |
| 28 | + (b'\xe8', b'\x85\x00\x78'), |
| 29 | + (b'\xcb', b'\x39\x2c\x00\x34\x02'), |
| 30 | + (b'\xf7', b'\x20'), |
| 31 | + (b'\xea', b'\x00\x00'), |
| 32 | + (b'\xc0', b'\x23'), # Power Control 1, VRH[5:0] |
| 33 | + (b'\xc1', b'\x10'), # Power Control 2, SAP[2:0], BT[3:0] |
| 34 | + (b'\xc5', b'\x3e\x28'), # VCM Control 1 |
| 35 | + (b'\xc7', b'\x86'), # VCM Control 2 |
| 36 | + (b'\x36', b'\x10'), # Memory Access Control |
| 37 | + (b'\x3a', b'\x55'), # Pixel Format |
| 38 | + (b'\xb1', b'\x00\x18'), # FRMCTR1 |
| 39 | + (b'\xb6', b'\x08\x82\x27'), # Display Function Control |
| 40 | + (b'\xf2', b'\x00'), # 3Gamma Function Disable |
| 41 | + (b'\x26', b'\x01'), # Gamma Curve Selected |
| 42 | + (b'\xe0', # Set Gamma |
| 43 | + b'\x0f\x31\x2b\x0c\x0e\x08\x4e\xf1\x37\x07\x10\x03\x0e\x09\x00'), |
| 44 | + (b'\xe1', # Set Gamma |
| 45 | + b'\x00\x0e\x14\x03\x11\x07\x31\xc1\x48\x08\x0f\x0c\x31\x36\x0f'), |
| 46 | + (b'\x11', None), |
| 47 | + (b'\x29', None), |
| 48 | + ): |
| 49 | + self.write(command, data) |
| 50 | + self.cs(1) |
| 51 | + utime.sleep_ms(50) |
| 52 | + |
| 53 | + def write(self, command=None, data=None): |
| 54 | + if command is not None: |
| 55 | + self.dc(0) |
| 56 | + self.spi.write(command) |
| 57 | + if data: |
| 58 | + self.dc(1) |
| 59 | + self.spi.write(data) |
| 60 | + |
| 61 | + def block(self, x0, y0, x1, y1): |
| 62 | + ustruct.pack_into('>HH', self._BUF, 0, x0, x1) |
| 63 | + self.write(b'\x2a', self._BUF) |
| 64 | + ustruct.pack_into('>HH', self._BUF, 0, y0, y1) |
| 65 | + self.write(b'\x2b', self._BUF) |
| 66 | + self.write(b'\x2c') |
| 67 | + self.dc(1) |
| 68 | + |
| 69 | + def clear(self, color=0x00): |
| 70 | + self.cs(0) |
| 71 | + self.block(0, 0, self.width, self.height) |
| 72 | + chunks, rest = divmod(self.width * self.height, 512) |
| 73 | + pixel = ustruct.pack('>H', color) |
| 74 | + if chunks: |
| 75 | + data = pixel * 512 |
| 76 | + for count in range(chunks): |
| 77 | + self.spi.write(data) |
| 78 | + if rest: |
| 79 | + self.spi.write(pixel * rest) |
| 80 | + self.cs(1) |
| 81 | + |
| 82 | + def __enter__(self): |
| 83 | + self.cs(0) |
| 84 | + return self |
| 85 | + |
| 86 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 87 | + self.cs(1) |
0 commit comments