package st7735 import ( "errors" "fmt" "image" "image/color" "image/draw" "time" "github.com/sirupsen/logrus" "go.maze.io/harmon/config" "go.maze.io/harmon/hardware" "go.maze.io/harmon/hardware/display" "go.maze.io/harmon/internal/spidev" "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" ) const ( ST7735_SWRESET = 0x01 ST7735_SLPIN = 0x10 ST7735_SLPOUT = 0x11 ST7735_FRMCTR1 = 0xB1 ST7735_FRMCTR2 = 0xB2 ST7735_FRMCTR3 = 0xB3 ST7735_INVCTR = 0xB4 ST7735_INVOFF = 0x20 ST7735_INVON = 0x21 ST7735_PWCTR1 = 0xC0 ST7735_PWCTR2 = 0xC1 ST7735_PWCTR4 = 0xC3 ST7735_PWCTR5 = 0xC4 ST7735_VMCTR1 = 0xC5 ST7735_MADCTL = 0x36 ST7735_COLMOD = 0x3A ST7735_CASET = 0x2A ST7735_RASET = 0x2B ST7735_RAMWR = 0x2C ST7735_GMCTRP1 = 0xE0 ST7735_GMCTRN1 = 0xE1 ST7735_NORON = 0x13 ST7735_DISPON = 0x29 ST7735_TFTWIDTH = 80 ST7735_TFTHEIGHT = 160 ST7735_COLS = 132 ST7735_ROWS = 162 ChunkSize = 4096 ) func init() { display.Register("st7735", newDriver) } func newDriver(config config.DisplayConfig) (hardware.Display, error) { var ( opts *display.Options //port spi.PortCloser //conn spi.Conn conn *spidev.SPI 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": "st7735", "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 } */ if conn, err = spidev.Open("/dev/spidev0.0"); err != nil { return nil, err } conn.SetMode(0) conn.SetBitsPerWord(8) //conn.SetLSBFirst(false) conn.SetSpeedHz(uint32(speed / physic.Hertz)) /* d := &Dev{ c: conn, dc: dc, rst: reset, backlight: bl, opts: Opts{ Width: byte(opts.W), Height: byte(opts.H), OffsetLeft: byte(ST7735_COLS-opts.W) / 2, OffsetTop: byte(ST7735_ROWS-opts.H) / 2, }, } return d, nil */ d := newDevice(conn, reset, dc, bl) d.Configure(Config{ Width: int16(opts.W), Height: int16(opts.H), Rotation: opts.Rotate, }) return d, nil } type Model uint8 // Device wraps an SPI connection. type Device struct { bus *spidev.SPI dcPin gpio.PinOut resetPin gpio.PinOut blPin gpio.PinOut width int16 height int16 columnOffset int16 rowOffset int16 rotation display.Rotation batchLength int16 model Model isBGR bool batchData []uint8 } // Config is the configuration for the display type Config struct { Width int16 Height int16 Rotation display.Rotation Model Model RowOffset int16 ColumnOffset int16 } // New creates a new ST7735 connection. The SPI wire must already be configured. // func newDevice(bus spi.Conn, resetPin, dcPin, blPin gpio.PinOut) *Device { func newDevice(bus *spidev.SPI, resetPin, dcPin, blPin gpio.PinOut) *Device { return &Device{ bus: bus, dcPin: dcPin, resetPin: resetPin, blPin: blPin, } } // Configure initializes the display with default configuration func (d *Device) Configure(cfg Config) { d.model = cfg.Model if cfg.Width != 0 { d.width = cfg.Width } else { if d.model == MINI80x160 { d.width = 80 } else { d.width = 128 } } if cfg.Height != 0 { d.height = cfg.Height } else { d.height = 160 } d.rotation = cfg.Rotation d.rowOffset = cfg.RowOffset d.columnOffset = cfg.ColumnOffset d.batchLength = d.width if d.height > d.width { d.batchLength = d.height } d.batchLength += d.batchLength & 1 d.batchData = make([]uint8, d.batchLength*2) // reset the device d.resetPin.Out(gpio.High) time.Sleep(5 * time.Millisecond) d.resetPin.Out(gpio.Low) time.Sleep(20 * time.Millisecond) d.resetPin.Out(gpio.High) time.Sleep(150 * time.Millisecond) println("display reset done") // Common initialization d.Command(SWRESET) time.Sleep(150 * time.Millisecond) d.Command(SLPOUT) time.Sleep(500 * time.Millisecond) d.Command(FRMCTR1) d.Data(0x01) d.Data(0x2C) d.Data(0x2D) d.Command(FRMCTR2) d.Data(0x01) d.Data(0x2C) d.Data(0x2D) d.Command(FRMCTR3) d.Data(0x01) d.Data(0x2C) d.Data(0x2D) d.Data(0x01) d.Data(0x2C) d.Data(0x2D) d.Command(INVCTR) d.Data(0x07) d.Command(PWCTR1) d.Data(0xA2) d.Data(0x02) d.Data(0x84) d.Command(PWCTR2) d.Data(0xC5) d.Command(PWCTR3) d.Data(0x0A) d.Data(0x00) d.Command(PWCTR4) d.Data(0x8A) d.Data(0x2A) d.Command(PWCTR5) d.Data(0x8A) d.Data(0xEE) d.Command(VMCTR1) d.Data(0x0E) d.Command(COLMOD) d.Data(0x05) if d.model == GREENTAB { d.InvertColors(false) } else if d.model == MINI80x160 { d.isBGR = true d.InvertColors(true) } println("display config done") // common color adjustment d.Command(GMCTRP1) d.Data(0x02) d.Data(0x1C) d.Data(0x07) d.Data(0x12) d.Data(0x37) d.Data(0x32) d.Data(0x29) d.Data(0x2D) d.Data(0x29) d.Data(0x25) d.Data(0x2B) d.Data(0x39) d.Data(0x00) d.Data(0x01) d.Data(0x03) d.Data(0x10) d.Command(GMCTRN1) d.Data(0x03) d.Data(0x1D) d.Data(0x07) d.Data(0x06) d.Data(0x2E) d.Data(0x2C) d.Data(0x29) d.Data(0x2D) d.Data(0x2E) d.Data(0x2E) d.Data(0x37) d.Data(0x3F) d.Data(0x00) d.Data(0x00) d.Data(0x02) d.Data(0x10) println("display color correction done") d.Command(NORON) time.Sleep(10 * time.Millisecond) d.Command(DISPON) time.Sleep(500 * time.Millisecond) if cfg.Model == MINI80x160 { d.Command(MADCTL) d.Data(0xC0) } d.SetRotation(d.rotation) println("display rotation set") d.blPin.Out(gpio.High) } // 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) { w, h := d.size() if x < 0 || y < 0 || x >= w || y >= h { 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) { if d.rotation == NO_ROTATION || d.rotation == ROTATION_180 { x += d.columnOffset y += d.rowOffset } else { x += d.rowOffset y += d.columnOffset } d.Tx([]uint8{CASET}, true) d.Tx([]uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)}, false) d.Tx([]uint8{RASET}, true) d.Tx([]uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)}, false) d.Command(RAMWR) } // SetScrollWindow sets an area to scroll with fixed top and bottom parts of the display func (d *Device) SetScrollArea(topFixedArea, bottomFixedArea int16) { d.Command(VSCRDEF) d.Tx([]uint8{ uint8(topFixedArea >> 8), uint8(topFixedArea), uint8(d.height - topFixedArea - bottomFixedArea>>8), uint8(d.height - topFixedArea - bottomFixedArea), uint8(bottomFixedArea >> 8), uint8(bottomFixedArea)}, false) } // SetScroll sets the vertical scroll address of the display. func (d *Device) SetScroll(line int16) { d.Command(VSCRSADD) d.Tx([]uint8{uint8(line >> 8), uint8(line)}, false) } // SpotScroll returns the display to its normal state func (d *Device) StopScroll() { d.Command(NORON) } // 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 := 65535 c1 := uint8(c565 >> 8) c2 := uint8(c565) for i = 0; i < d.batchLength; i++ { d.batchData[i*2] = c1 d.batchData[i*2+1] = c2 } i = width * height for i > 0 { if i >= d.batchLength { d.Tx(d.batchData, false) } else { d.Tx(d.batchData[:i*2], false) } i -= d.batchLength } return nil } // FillRectangle fills a rectangle at a given coordinates with a buffer func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error { k, l := d.size() if x < 0 || y < 0 || width <= 0 || height <= 0 || x >= k || (x+width) > k || y >= l || (y+height) > l { //return errors.New("rectangle coordinates outside display area") return fmt.Errorf("rectangle [%d %d %d %d] outside of [0 0 %d %d]", x, y, width, height, k, l) } k = width * height l = int16(len(buffer)) if k != l { return errors.New("buffer length does not match with rectangle size") } d.setWindow(x, y, width, height) offset := int16(0) for k > 0 { for i := int16(0); i < d.batchLength; i++ { if offset+i < l { c565 := 65535 c1 := uint8(c565 >> 8) c2 := uint8(c565) d.batchData[i*2] = c1 d.batchData[i*2+1] = c2 } } if k >= d.batchLength { d.Tx(d.batchData, false) } else { d.Tx(d.batchData[:k*2], false) } 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 break case 1: madctl = MADCTL_MY | MADCTL_MV break case 2: break case 3: madctl = MADCTL_MX | MADCTL_MV break } if d.isBGR { madctl |= MADCTL_BGR } d.Command(MADCTL) d.Data(madctl) } // Command sends a command to the display func (d *Device) Command(command uint8) { d.Tx([]byte{command}, true) } // Command sends a data to the display func (d *Device) Data(data uint8) { d.Tx([]byte{data}, false) } // Tx sends data to the display func (d *Device) Tx(data []byte, isCommand bool) { d.dcPin.Out(gpio.Level(!isCommand)) //d.bus.Tx(data, nil) d.bus.Transfer([]spidev.Transfer{{Tx: data}}) } // 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) } } // InverColors inverts the colors of the screen func (d *Device) InvertColors(invert bool) { if invert { d.Command(INVON) } else { d.Command(INVOFF) } } // IsBGR changes the color mode (RGB/BGR) func (d *Device) IsBGR(bgr bool) { d.isBGR = bgr } /* // Dev is a handle to a ST7735 type Dev struct { c conn.Conn // dc low when sending a command, high when sending data. dc gpio.PinOut // rst reset pin, active low. rst gpio.PinOut // backlight pin backlight gpio.PinOut opts Opts } // Opts contains the configuration fot the ST7735 device type Opts struct { Width byte Height byte OffsetLeft byte OffsetTop byte } var DefaultOpts = Opts{ Width: ST7735_TFTWIDTH, Height: ST7735_TFTHEIGHT, OffsetLeft: (ST7735_COLS - ST7735_TFTWIDTH) / 2, // (132-80)/2 = 26 OffsetTop: (ST7735_ROWS - ST7735_TFTHEIGHT) / 2, // (162-160)/2 = 1 } // New opens a handle to a ST7735 func New(p spi.Port, dc gpio.PinOut, rst gpio.PinOut, backlight gpio.PinOut, o *Opts) (*Dev, error) { c, err := p.Connect(4000*physic.KiloHertz, spi.Mode0, 8) if err != nil { return nil, errors.New("could not connect to device") } d := &Dev{ c: c, dc: dc, rst: rst, backlight: backlight, opts: *o, } return d, nil } func (d *Dev) Init() error { if err := d.Backlight(true); err != nil { return err } invert := commandAndData{[]byte{ST7735_INVON}, nil, 0} // don't invert if false { invert = commandAndData{[]byte{ST7735_INVOFF}, nil, 0} // invert } width := d.opts.Width height := d.opts.Height offsetLeft := d.opts.OffsetLeft offsetTop := d.opts.OffsetTop init := []commandAndData{ {[]byte{ST7735_SWRESET}, nil, 150 * time.Millisecond}, // software reset {[]byte{ST7735_SLPOUT}, nil, 500 * time.Millisecond}, // out of sleep mode {[]byte{ST7735_FRMCTR1}, []byte{0x01, 0x2C, 0x2D}, 0}, // frame rate ctrl - normal mode, rate = fosc/(1x2+40) * (LINE+2C+2D) {[]byte{ST7735_FRMCTR2}, []byte{0x01, 0x2C, 0x2D}, 0}, // frame rate crtl - idle mode, rate = fosc(1x2+40) * (LINE+2C+2D) {[]byte{ST7735_FRMCTR3}, []byte{0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D}, 0}, // frame rate ctrl - partial mode {[]byte{ST7735_INVCTR}, []byte{0x07}, 0}, // display inversion ctrl - no inversion {[]byte{ST7735_PWCTR1}, []byte{0xA2, 0x02, 0x84}, 0}, // power control, -4.6V, auto mode {[]byte{ST7735_PWCTR2}, []byte{0x0A, 0x00}, 0}, // power control, Opamp current small, boost frequency {[]byte{ST7735_PWCTR4}, []byte{0x8A, 0x2A}, 0}, // power control, BCLK/2, Opamp current small & Medium low {[]byte{ST7735_PWCTR5}, []byte{0x8A, 0xEE}, 0}, // power control {[]byte{ST7735_VMCTR1}, []byte{0x0E}, 0}, // power control invert, {[]byte{ST7735_MADCTL}, []byte{0xC8}, 0}, // memory access control (directions), row addr/col addr, bottom to top refresh {[]byte{ST7735_COLMOD}, []byte{0x05}, 0}, // set color mode, 16-bit color {[]byte{ST7735_CASET}, []byte{0x00, offsetLeft, 0x00, width + offsetLeft - 1}, 0}, // Column addr set, XSTART = 0, XEND = ROWS-height {[]byte{ST7735_RASET}, []byte{0x00, offsetTop, 0x00, height + offsetTop - 1}, 0}, // Row addr set, XSTART = 0, XEND = COLS-width {[]byte{ST7735_GMCTRP1}, []byte{0x02, 0x1c, 0x07, 0x12, // set gamma 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2B, 0x39, 0x00, 0x01, 0x03, 0x10}, 0}, {[]byte{ST7735_GMCTRN1}, []byte{0x03, 0x1d, 0x07, 0x06, // set gamma 0x2E, 0x2C, 0x29, 0x2D, 0x2E, 0x2E, 0x37, 0x3F, 0x00, 0x00, 0x02, 0x10}, 0}, {[]byte{ST7735_NORON}, nil, 100 * time.Millisecond}, // normal display on {[]byte{ST7735_DISPON}, nil, 100 * time.Millisecond}, // display on } return d.sendBatch(init) } func (d *Dev) Powersave() error { return d.sendCommand([]byte{ST7735_SLPIN}) } func (d *Dev) SetBacklight(value bool) { if d.backlight == nil { return } if value { d.backlight.Out(gpio.High) } else { d.backlight.Out(gpio.Low) } } func (d *Dev) SetWindow(x0, y0, x1, y1 int) error { y0 += int(d.opts.OffsetTop) y1 += int(d.opts.OffsetTop) x0 += int(d.opts.OffsetLeft) x1 += int(d.opts.OffsetLeft) commands := []commandAndData{ {[]byte{ST7735_CASET}, []byte{byte(x0 >> 8), byte(x0), byte(x1 >> 8), byte(x1)}, 0}, // column addr set {[]byte{ST7735_RASET}, []byte{byte(y0 >> 8), byte(y0), byte(y1 >> 8), byte(y1)}, 0}, // row addr set {[]byte{ST7735_RAMWR}, nil, 0}, // write to RAM } return d.sendBatch(commands) } func (d *Dev) DisplayImage(x, y int, img *image.RGBA) error { offsetBounds := img.Bounds().Add(image.Point{X: x, Y: y}) maxBounds := image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{int(d.opts.Width), int(d.opts.Height)}} offsetBounds = offsetBounds.Intersect(maxBounds) bounds := offsetBounds.Sub(image.Point{X: x, Y: y}) err := d.SetWindow(offsetBounds.Min.X, offsetBounds.Min.Y, offsetBounds.Max.X-1, offsetBounds.Max.Y-1) if err != nil { return err } subImg := img.SubImage(bounds) buf := []byte{} for x := bounds.Min.X; x < bounds.Max.X; x++ { for y := bounds.Min.Y; y < bounds.Max.Y; y++ { c := subImg.At(x, y) cd := RGBATo565(c.(color.RGBA)) buf = append(buf, byte(cd>>8), byte(cd)) } } return d.sendData(buf) } func (d *Dev) Display(data []byte) error { err := d.SetWindow(0, 0, int(d.opts.Width-1), int(d.opts.Height-1)) if err != nil { return err } return d.sendData(data) } func (d *Dev) Halt() error { d.SetBacklight(false) return d.Powersave() } func (d *Dev) sendCommand(c []byte) error { if err := d.dc.Out(gpio.Low); err != nil { return err } return d.c.Tx(c, nil) } func (d *Dev) sendData(c []byte) error { if err := d.dc.Out(gpio.High); err != nil { return err } for offset := 0; offset < len(c); offset += ChunkSize { end := offset + ChunkSize if end > len(c) { end = len(c) } if err := d.c.Tx(c[offset:end], nil); err != nil { return err } } return nil } func (d *Dev) sendBatch(commands []commandAndData) error { for _, cad := range commands { if err := d.sendCommand(cad.cmd); err != nil { return err } if len(cad.data) == 0 { continue } if err := d.sendData(cad.data); err != nil { return err } if cad.sleep > 0 { time.Sleep(cad.sleep) } } return nil } type commandAndData struct { cmd []byte data []byte sleep time.Duration } // 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(i, j int) color.Color { return color.Black } func (d *Device) Backlight(on bool) error { return d.blPin.Out(gpio.Level(!on)) } func (d *Device) Bounds() image.Rectangle { return image.Rect(0, 0, int(d.width), int(d.height)) } func (Device) Clear() {} func (d *Device) Fill(c color.Color) error { img := image.NewRGBA(d.Bounds()) draw.Draw(img, img.Rect, &image.Uniform{c}, image.Point{}, draw.Src) //d.DisplayImage(0, 0, img) return nil } func (d *Device) ColorModel() color.Model { return color.RGBAModel } func (d *Device) Set(x, y int, c color.Color) { /* d.SetWindow(x, y, x, y) var buf []byte cd := RGBATo565(color.RGBAModel.Convert(c).(color.RGBA)) buf = append(buf, byte(cd>>8), byte(cd)) d.sendData(buf) */ d.SetPixel(int16(x), int16(y), color.RGBAModel.Convert(c).(color.RGBA)) } func (Device) Type() string { return "st7735" } func (Device) Refresh() error { return nil } func (d *Device) Draw(r image.Rectangle, src image.Image, sp image.Point) error { buffer := make([]color.RGBA, 0, int(d.width)*int(d.height)) for y := 0; y < int(d.height); y++ { for x := 0; x < int(d.width); x++ { r, g, b, _ := src.At(x, y).RGBA() buffer = append(buffer, color.RGBA{ R: uint8(r >> 8), G: uint8(g >> 8), B: uint8(b >> 8), A: 0xff, }) } } return d.FillRectangleWithBuffer(0, 0, d.width, d.height, buffer) } func (d *Device) Size() image.Point { return image.Pt(int(d.width), int(d.height)) } func (Device) Halt() error { return nil }