// Package st7789 implements a driver for the ST7789 TFT displays, it comes in various screen sizes. // // Datasheets: https://cdn-shop.adafruit.com/product-files/3787/3787_tft_QT154H2201__________20190228182902.pdf // // http://www.newhavendisplay.com/appnotes/datasheets/LCDs/ST7789V.pdf package st7789 import ( "errors" "fmt" "image" "image/color" "math" "time" "github.com/sirupsen/logrus" "periph.io/x/conn/v3/gpio" "periph.io/x/conn/v3/physic" "periph.io/x/conn/v3/spi" "periph.io/x/conn/v3/spi/spireg" "go.maze.io/harmon/config" "go.maze.io/harmon/hardware" "go.maze.io/harmon/hardware/display" ) func init() { display.Register("st7789", newDriver) } var ( errOutOfBounds = errors.New("rectangle coordinates outside display area") ) // FrameRate controls the frame rate used by the display. type FrameRate uint8 type Device struct { conn spi.Conn reset gpio.PinOut dcPin gpio.PinOut resetPin gpio.PinOut blPin gpio.PinOut width int16 height int16 columnOffsetCfg int16 rowOffsetCfg int16 columnOffset int16 rowOffset int16 rotation display.Rotation frameRate FrameRate batchLength int32 isBGR bool vSyncLines int16 } // Config is the configuration for the display type Config struct { Width int16 Height int16 Rotation display.Rotation RowOffset int16 ColumnOffset int16 FrameRate FrameRate VSyncLines int16 } func newDriver(config config.DisplayConfig) (hardware.Display, error) { var ( opts *display.Options port spi.PortCloser conn spi.Conn reset, dc, bl gpio.PinOut err error ) if opts, err = display.ParseOptions(config, 240, 240); err != nil { return nil, err } log := logrus.WithFields(logrus.Fields{ "type": "st7789", "size": fmt.Sprintf("%dx%d", opts.W, opts.H), "rotate": opts.Rotate, }) log.Debug("new driver") if reset, err = hardware.LookupPin(config.Reset); err != nil { return nil, err } if dc, err = hardware.LookupPin(config.DC); err != nil { return nil, err } if bl, err = hardware.LookupPin(config.BL); err != nil { return nil, err } const speed = 40000000 * physic.Hertz log.WithFields(logrus.Fields{ "port": config.Port, "pin_reset": reset, "pin_dc": dc, "pin_bl": bl, "speed": speed, "bits": 8, "mode": spi.Mode0, }).Debug("opening SPI port") if port, err = spireg.Open(config.Port); err != nil { return nil, err } if conn, err = port.Connect(speed, spi.Mode0, 8); err != nil { _ = port.Close() return nil, err } return newDisplay(conn, reset, dc, bl, opts) } func newDisplay(conn spi.Conn, reset, dc, bl gpio.PinOut, opts *display.Options) (d *Device, err error) { d = &Device{ conn: conn, resetPin: reset, dcPin: dc, blPin: bl, } d.Configure(Config{ Width: int16(opts.W), Height: int16(opts.H), Rotation: opts.Rotate, FrameRate: FRAMERATE_60, }) return d, nil } // Configure initializes the display with default configuration func (d *Device) Configure(cfg Config) { if cfg.Width != 0 { d.width = cfg.Width } else { d.width = 240 } if cfg.Height != 0 { d.height = cfg.Height } else { d.height = 240 } logrus.WithFields(logrus.Fields{ "driver": "st7789", "width": d.width, "height": d.height, }).Warn("yello!") d.rotation = cfg.Rotation d.rowOffsetCfg = cfg.RowOffset d.columnOffsetCfg = cfg.ColumnOffset if cfg.FrameRate != 0 { d.frameRate = cfg.FrameRate } else { d.frameRate = FRAMERATE_60 } if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 { d.vSyncLines = cfg.VSyncLines } else { d.vSyncLines = 16 } d.batchLength = int32(d.width) if d.height > d.width { d.batchLength = int32(d.height) } d.batchLength += d.batchLength & 1 // Reset the device d.resetPin.Out(gpio.High) time.Sleep(500 * time.Millisecond) d.resetPin.Out(gpio.Low) time.Sleep(500 * time.Millisecond) d.resetPin.Out(gpio.High) time.Sleep(500 * time.Millisecond) // Common initialization d.sendCommand(0x11) time.Sleep(150 * time.Millisecond) d.sendCommand(0x36, 0x00) d.sendCommand(0x3A, 0x05) d.sendCommand(0xB2, 0x0C, 0x0C) d.sendCommand(0xB7, 0x35) d.sendCommand(0xBB, 0x1A) d.sendCommand(0xC0, 0x2C) d.sendCommand(0xC2, 0x01) d.sendCommand(0xC3, 0x0B) d.sendCommand(0xC4, 0x20) d.sendCommand(0xC6, 0x0F) d.sendCommand(0xD0, 0xA4, 0xA1) d.sendCommand(0x21) d.sendCommand(ST7789_MADCTL, 0x78) d.sendCommand(0xE0, 0x00, 0x19, 0x1E, 0x0A, 0x09, 0x15, 0x3D, 0x44, 0x51, 0x12, 0x03, 0x00, 0x3F, 0x3F) d.sendCommand(0xE1, 0x00, 0x18, 0x1E, 0x0A, 0x09, 0x25, 0x3F, 0x43, 0x52, 0x33, 0x03, 0x00, 0x3F, 0x3F) d.sendCommand(0x29) time.Sleep(100 * time.Millisecond) d.blPin.Out(gpio.High) // Backlight ON } // Sync waits for the display to hit the next VSYNC pause func (d *Device) Sync() { d.SyncToScanLine(0) } // SyncToScanLine waits for the display to hit a specific scanline // // A scanline value of 0 will forward to the beginning of the next VSYNC, // even if the display is currently in a VSYNC pause. // // Syncline values appear to increment once for every two vertical // lines on the display. // // NOTE: Use GetHighestScanLine and GetLowestScanLine to obtain the highest // and lowest useful values. Values are affected by front and back porch // vsync settings (derived from VSyncLines configuration option). func (d *Device) SyncToScanLine(scanline uint16) { scan := d.GetScanLine() // Sometimes GetScanLine returns erroneous 0 on first call after draw, so double check if scan == 0 { scan = d.GetScanLine() } if scanline == 0 { // we dont know where we are in an ongoing vsync so go around for scan < 1 { time.Sleep(1 * time.Millisecond) scan = d.GetScanLine() } for scan > 0 { scan = d.GetScanLine() } } else { // go around unless we're very close to the target for scan > scanline+4 { time.Sleep(1 * time.Millisecond) scan = d.GetScanLine() } for scan < scanline { scan = d.GetScanLine() } } } func (d *Device) Backlight(on bool) error { return d.blPin.Out(gpio.Level(on)) } // GetScanLine reads the current scanline value from the display func (d *Device) GetScanLine() uint16 { data := []uint8{0x00, 0x00} //d.Rx(GSCAN, data) return uint16(data[0])<<8 + uint16(data[1]) } // GetHighestScanLine calculates the last scanline id in the frame before VSYNC pause func (d *Device) GetHighestScanLine() uint16 { // Last scanline id appears to be backporch/2 + 320/2 return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 160 } // GetLowestScanLine calculate the first scanline id to appear after VSYNC pause func (d *Device) GetLowestScanLine() uint16 { // First scanline id appears to be backporch/2 + 1 return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 1 } // Display does nothing, there's no buffer as it might be too big for some boards func (d *Device) Display() error { return nil } // SetPixel sets a pixel in the screen func (d *Device) SetPixel(x int16, y int16, c color.RGBA) { if x < 0 || y < 0 || (((d.rotation == NO_ROTATION || d.rotation == ROTATION_180) && (x >= d.width || y >= d.height)) || ((d.rotation == ROTATION_90 || d.rotation == ROTATION_270) && (x >= d.height || y >= d.width))) { return } d.FillRectangle(x, y, 1, 1, c) } // setWindow prepares the screen to be modified at a given rectangle func (d *Device) setWindow(x, y, w, h int16) { x0 := x + d.columnOffset y0 := y + d.rowOffset x1 := x + w - 1 y1 := y + h - 1 d.sendCommand(ST7789_CASET, byte(x0>>8), byte(x0), byte(x1>>8), byte(x1)) d.sendCommand(ST7789_RASET, byte(y0>>8), byte(y0), byte(y1>>8), byte(y1)) d.sendCommand(ST7789_RAMWR) } // FillRectangle fills a rectangle at a given coordinates with a color func (d *Device) FillRectangle(x, y, width, height int16, c color.RGBA) error { k, i := d.size() if x < 0 || y < 0 || width <= 0 || height <= 0 || x >= k || (x+width) > k || y >= i || (y+height) > i { return errors.New("rectangle coordinates outside display area") } d.setWindow(x, y, width, height) c565 := RGBATo565(c) c1 := uint8(c565 >> 8) c2 := uint8(c565) data := make([]uint8, d.batchLength*2) for i := int32(0); i < d.batchLength; i++ { data[i*2] = c1 data[i*2+1] = c2 } j := int32(width) * int32(height) for j > 0 { if j >= d.batchLength { d.sendData(data) } else { d.sendData(data[:j*2]) } j -= d.batchLength } return nil } // FillRectangleWithBuffer fills buffer with a rectangle at a given coordinates. func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error { i, j := d.size() if x < 0 || y < 0 || width <= 0 || height <= 0 || x >= i || (x+width) > i || y >= j || (y+height) > j { return errors.New("rectangle coordinates outside display area") } if int32(width)*int32(height) != int32(len(buffer)) { return errors.New("buffer length does not match with rectangle size") } d.setWindow(x, y, width, height) k := int32(width) * int32(height) data := make([]uint8, d.batchLength*2) offset := int32(0) for k > 0 { for i := int32(0); i < d.batchLength; i++ { if offset+i < int32(len(buffer)) { c565 := RGBATo565(buffer[offset+i]) c1 := uint8(c565 >> 8) c2 := uint8(c565) data[i*2] = c1 data[i*2+1] = c2 } } if k >= d.batchLength { d.sendData(data) } else { d.sendData(data[:k*2]) } k -= d.batchLength offset += d.batchLength } return nil } // DrawFastVLine draws a vertical line faster than using SetPixel func (d *Device) DrawFastVLine(x, y0, y1 int16, c color.RGBA) { if y0 > y1 { y0, y1 = y1, y0 } d.FillRectangle(x, y0, 1, y1-y0+1, c) } // DrawFastHLine draws a horizontal line faster than using SetPixel func (d *Device) DrawFastHLine(x0, x1, y int16, c color.RGBA) { if x0 > x1 { x0, x1 = x1, x0 } d.FillRectangle(x0, y, x1-x0+1, 1, c) } // FillScreen fills the screen with a given color func (d *Device) FillScreen(c color.RGBA) { if d.rotation == NO_ROTATION || d.rotation == ROTATION_180 { d.FillRectangle(0, 0, d.width, d.height, c) } else { d.FillRectangle(0, 0, d.height, d.width, c) } } // SetRotation changes the rotation of the device (clock-wise) func (d *Device) SetRotation(rotation display.Rotation) { /* madctl := uint8(0) switch rotation % 4 { case 0: madctl = MADCTL_MX | MADCTL_MY d.rowOffset = d.rowOffsetCfg d.columnOffset = d.columnOffsetCfg break case 1: madctl = MADCTL_MY | MADCTL_MV d.rowOffset = d.columnOffsetCfg d.columnOffset = d.rowOffsetCfg break case 2: d.rowOffset = 0 d.columnOffset = 0 break case 3: madctl = MADCTL_MX | MADCTL_MV d.rowOffset = 0 d.columnOffset = 0 break } if d.isBGR { madctl |= MADCTL_BGR } d.sendCommand(ST7789_MADCTL, madctl) */ } // Rx reads data from the display func (d *Device) Rx(command uint8, data []byte) { d.dcPin.Out(gpio.Low) sendCommand(d.conn, command) d.dcPin.Out(gpio.High) for i := range data { data[i], _ = sendCommand(d.conn, 0xFF) } } func sendCommand(bus spi.Conn, command byte) (byte, error) { answer := []byte{0} err := bus.Tx( []byte{command}, []byte(""), ) if err != nil { return 0, err } return answer[0], nil } // Size returns the current size of the display. func (d *Device) size() (w, h int16) { if d.rotation == NO_ROTATION || d.rotation == ROTATION_180 { return d.width, d.height } return d.height, d.width } // EnableBacklight enables or disables the backlight func (d *Device) EnableBacklight(enable bool) { if enable { d.blPin.Out(gpio.High) } else { d.blPin.Out(gpio.Low) } } // InvertColors inverts the colors of the screen func (d *Device) InvertColors(invert bool) { if invert { d.sendCommand(ST7789_INVON) } else { d.sendCommand(ST7789_INVOFF) } } // IsBGR changes the color mode (RGB/BGR) func (d *Device) IsBGR(bgr bool) { d.isBGR = bgr } // SetScrollArea sets an area to scroll with fixed top and bottom parts of the display. func (d *Device) SetScrollArea(topFixedArea, bottomFixedArea int16) { d.sendCommand(ST7789_VSCRDEF, uint8(topFixedArea>>8), uint8(topFixedArea), uint8(d.height-topFixedArea-bottomFixedArea>>8), uint8(d.height-topFixedArea-bottomFixedArea), uint8(bottomFixedArea>>8), uint8(bottomFixedArea)) } // SetScroll sets the vertical scroll address of the display. func (d *Device) SetScroll(line int16) { d.sendCommand(ST7789_VSCRSADD, uint8(line>>8), uint8(line)) } // StopScroll returns the display to its normal state. func (d *Device) StopScroll() { d.sendCommand(ST7789_NORON) } // RGBATo565 converts a color.RGBA to uint16 used in the display func RGBATo565(c color.RGBA) uint16 { r, g, b, _ := c.RGBA() return uint16((r & 0xF800) + ((g & 0xFC00) >> 5) + ((b & 0xF800) >> 11)) } func (d *Device) At(x, y int) color.Color { return color.Black } func (d *Device) Bounds() image.Rectangle { if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 { return image.Rect(0, 0, int(d.height), int(d.width)) } return image.Rect(0, 0, int(d.width), int(d.height)) } func (d *Device) Clear() { d.FillRectangle(0, 0, d.width, d.height, color.RGBA{A: 0xff}) } func (Device) ColorModel() color.Model { return color.RGBAModel } func (d *Device) Fill(c color.Color) error { rgba := color.RGBAModel.Convert(c).(color.RGBA) d.FillRectangle(0, 0, d.width, d.height, rgba) return nil } func (d *Device) sendData(data []byte) (err error) { if err = d.dcPin.Out(gpio.High); err != nil { return } return d.conn.Tx(data, nil) } func (d *Device) sendCommand(cmd byte, args ...byte) (err error) { if err = d.dcPin.Out(gpio.Low); err != nil { return } if err = d.conn.Tx([]byte{cmd}, nil); err != nil { return } if len(args) > 0 { return d.sendData(args) } return } func (d *Device) Set(x, y int, c color.Color) { var ( rc = RGBATo565(color.RGBAModel.Convert(c).(color.RGBA)) xo = x + int(d.columnOffset) yo = y + int(d.rowOffset) ) d.sendCommand(0x2A, byte(xo>>8), byte(xo), byte(xo>>8), byte(xo)) // column addr d.sendCommand(0x2B, byte(yo>>8), byte(yo), byte(yo>>8), byte(yo)) // row addr d.sendCommand(0x2C, byte(rc>>8), byte(rc)) // pixel } func (d *Device) Size() image.Point { if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 { return image.Pt(int(d.height), int(d.width)) } return image.Pt(int(d.width), int(d.height)) } func (Device) Type() string { return "st7789" } func (d *Device) Draw(r image.Rectangle, src image.Image, sp image.Point) error { //draw.Draw(d, r, src, sp, draw.Src) logrus.Warnf("make slice %d (%dx%d)", d.height*d.width, d.height, d.width) var ( buffer = make([]color.RGBA, int(d.height)*int(d.width)) bounds = src.Bounds() ) for y := 0; y < bounds.Max.Y && y < int(d.height); y++ { for x := 0; x < bounds.Max.X && x < int(d.width); x++ { r, g, b, a := src.At(x, y).RGBA() buffer[y*int(d.width)+x] = color.RGBA{R: uint8(r / 0x100), G: uint8(g / 0x100), B: uint8(b / 0x100), A: uint8(a / 0x100)} } } return d.FillRectangleWithBuffer(0, 0, d.width, d.height, buffer) } func (Device) Halt() error { return nil } func (Device) Refresh() error { return nil }