|
| 1 | +import struct |
| 2 | +import time |
| 3 | + |
| 4 | + |
| 5 | +class ST7735R: |
| 6 | + """A minimal driver for the 128x128 version of the ST7735 SPI display.""" |
| 7 | + |
| 8 | + width = 128 |
| 9 | + height = 128 |
| 10 | + |
| 11 | + def __init__(self, spi, dc, rotation=0x06): |
| 12 | + self.spi = spi |
| 13 | + self.dc = dc |
| 14 | + self.dc.switch_to_output(value=1) |
| 15 | + self.rotation = rotation |
| 16 | + time.sleep(0.1) |
| 17 | + for command, data, delay in ( |
| 18 | + (b'\x01', b'', 120), |
| 19 | + (b'\x11', b'', 120), |
| 20 | + (b'\x36', bytes(((rotation & 0x07) << 5,)), 0), |
| 21 | + (b'\x3a', b'\x05', 0), |
| 22 | + (b'\xb4', b'\x07', 0), |
| 23 | + (b'\xb1', b'\x01\x2c\x2d', 0), |
| 24 | + (b'\xb2', b'\x01\x2c\x2d', 0), |
| 25 | + (b'\xb3', b'\x01\x2c\x2d\x01\x2c\x2d', 0), |
| 26 | + (b'\xc0', b'\x02\x02\x84', 0), |
| 27 | + (b'\xc1', b'\xc5', 0), |
| 28 | + (b'\xc2', b'\x0a\x00', 0), |
| 29 | + (b'\xc3', b'\x8a\x2a', 0), |
| 30 | + (b'\xc4', b'\x8a\xee', 0), |
| 31 | + (b'\xc5', b'\x0e', 0), |
| 32 | + (b'\x20', b'', 0), |
| 33 | + (b'\xe0', b'\x02\x1c\x07\x12\x37\x32\x29\x2d' |
| 34 | + b'\x29\x25\x2B\x39\x00\x01\x03\x10', 0), |
| 35 | + (b'\xe1', b'\x03\x1d\x07\x06\x2E\x2C\x29\x2D' |
| 36 | + b'\x2E\x2E\x37\x3F\x00\x00\x02\x10', 0), |
| 37 | + (b'\x13', b'', 10), |
| 38 | + (b'\x29', b'', 120), |
| 39 | + ): |
| 40 | + self.write(command, data) |
| 41 | + time.sleep(delay / 1000) |
| 42 | + self.dc.value = 0 |
| 43 | + |
| 44 | + def block(self, x0, y0, x1, y1): |
| 45 | + """Prepare for updating a block of the screen.""" |
| 46 | + if self.rotation & 0x01: |
| 47 | + x0 += 3 |
| 48 | + x1 += 3 |
| 49 | + y0 += 2 |
| 50 | + y1 += 2 |
| 51 | + else: |
| 52 | + x0 += 2 |
| 53 | + x1 += 2 |
| 54 | + y0 += 3 |
| 55 | + y1 += 3 |
| 56 | + xpos = struct.pack('>HH', x0, x1) |
| 57 | + ypos = struct.pack('>HH', y0, y1) |
| 58 | + self.write(b'\x2a', xpos) |
| 59 | + self.write(b'\x2b', ypos) |
| 60 | + self.write(b'\x2c') |
| 61 | + self.dc.value = 1 |
| 62 | + |
| 63 | + def write(self, command=None, data=None): |
| 64 | + """Send command and/or data to the display.""" |
| 65 | + |
| 66 | + if command is not None: |
| 67 | + self.dc.value = 0 |
| 68 | + self.spi.write(command) |
| 69 | + if data: |
| 70 | + self.dc.value = 1 |
| 71 | + self.spi.write(data) |
| 72 | + |
| 73 | + def clear(self, color=0x00): |
| 74 | + """Clear the display with the given color.""" |
| 75 | + |
| 76 | + self.block(0, 0, self.width - 1, self.height - 1) |
| 77 | + pixel = color.to_bytes(2, 'big') |
| 78 | + data = pixel * 256 |
| 79 | + for count in range(self.width * self.height // 256): |
| 80 | + self.write(None, data) |
0 commit comments