Checkpoint
This commit is contained in:
125 files changed
+59376
No files matched your search
@@ -0,0 +1,562 @@
|
||||
package ssd1306
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||
"periph.io/x/conn/v3/i2c"
|
||||
"periph.io/x/conn/v3/i2c/i2creg"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
"periph.io/x/devices/v3/ssd1306/image1bit"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("ssd1306", newDevice)
|
||||
}
|
||||
|
||||
// DefaultOpts is the recommended default options.
|
||||
var DefaultOpts = Opts{
|
||||
W: 128,
|
||||
H: 64,
|
||||
Addr: 0x3c,
|
||||
Rotated: false,
|
||||
MirrorVertical: false,
|
||||
MirrorHorizontal: false,
|
||||
Sequential: false,
|
||||
SwapTopBottom: false,
|
||||
}
|
||||
|
||||
// Opts defines the options for the device.
|
||||
type Opts struct {
|
||||
W int
|
||||
H int
|
||||
|
||||
// Addr is the I2C address.
|
||||
Addr uint16
|
||||
|
||||
// Rotated determines if the display is rotated by 180°.
|
||||
//
|
||||
// Deprecated: Use MirrorVertical and MirrorHorizontal instead.
|
||||
Rotated bool
|
||||
|
||||
// Sequential corresponds to the Sequential/Alternative COM pin configuration
|
||||
// in the OLED panel hardware. Try toggling this if half the rows appear to be
|
||||
// missing on your display.
|
||||
Sequential bool
|
||||
|
||||
// MirrorVertical corresponds to the COM remap configuration in the OLED panel
|
||||
// hardware. Try toggling this if the display is flipped vertically.
|
||||
// Overwrites Rotated.
|
||||
MirrorVertical bool
|
||||
|
||||
// MirrorHorizontal corresponds to the SEG remap configuration in the OLED panel
|
||||
// hardware. Try toggling this if the display is flipped horizontally.
|
||||
// Overwrites Rotated.
|
||||
MirrorHorizontal bool
|
||||
|
||||
// SwapTopBottom corresponds to the Left/Right remap COM pin configuration in
|
||||
// the OLED panel hardware. Try toggling this if the top and bottom halves of
|
||||
// your display are swapped.
|
||||
SwapTopBottom bool
|
||||
}
|
||||
|
||||
type Dev struct {
|
||||
// Communication
|
||||
c conn.Conn
|
||||
dc gpio.PinOut
|
||||
spi bool
|
||||
|
||||
// Display size controlled by the SSD1306.
|
||||
rect image.Rectangle
|
||||
|
||||
// Mutable
|
||||
// See page 25 for the GDDRAM pages structure.
|
||||
// Narrow screen will waste the end of each page.
|
||||
// Short screen will ignore the lower pages.
|
||||
// There is 8 pages, each covering an horizontal band of 8 pixels high (1
|
||||
// byte) for 128 bytes.
|
||||
// 8*128 = 1024 bytes total for 128x64 display.
|
||||
buffer []byte
|
||||
// next is lazy initialized on first Draw(). Write() skips this buffer.
|
||||
next *image1bit.VerticalLSB
|
||||
startPage, endPage int
|
||||
startCol, endCol int
|
||||
scrolled bool
|
||||
halted bool
|
||||
}
|
||||
|
||||
func newDevice(config *config.Display) (display.Display, error) {
|
||||
width, height, err := display.ParseSize(config.Size, DefaultOpts.W, DefaultOpts.H)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||
}
|
||||
|
||||
opts := new(Opts)
|
||||
*opts = DefaultOpts
|
||||
opts.W = width
|
||||
opts.H = height
|
||||
|
||||
if config.Bus == "" || strings.HasPrefix(config.Bus, "i2c") {
|
||||
return newI2C(config, opts)
|
||||
}
|
||||
return newSPI(config, opts)
|
||||
}
|
||||
|
||||
func newI2C(config *config.Display, opts *Opts) (display.Display, error) {
|
||||
addr, err := display.ParseI2CAddress(config.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid I2C address %q: %w", config.Address, err)
|
||||
}
|
||||
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"type": "ssd1306",
|
||||
"size": fmt.Sprintf("%dx%d", opts.W, opts.H),
|
||||
"mode": "i2c",
|
||||
})
|
||||
log.WithField("bus", config.Bus).Debug("opening I2C bus")
|
||||
|
||||
bus, err := i2creg.Open(config.Bus)
|
||||
if err != nil {
|
||||
log.WithField("bus", config.Bus).WithError(err).Warn("opening I2C bus failed")
|
||||
return nil, fmt.Errorf("error opening I2C bus %q: %w", config.Bus, err)
|
||||
}
|
||||
|
||||
log = log.WithFields(logrus.Fields{
|
||||
"i2c_bus": bus.String(),
|
||||
"i2c_addr": fmt.Sprintf("%#02x", addr),
|
||||
})
|
||||
log.Debug("starting display")
|
||||
return newDev(&i2c.Dev{Bus: bus, Addr: addr}, opts, false, nil)
|
||||
}
|
||||
|
||||
func newSPI(config *config.Display, opts *Opts) (display.Display, error) {
|
||||
var (
|
||||
dc gpio.PinOut
|
||||
bits = 9
|
||||
)
|
||||
if config.DC != "" {
|
||||
if dc = gpioreg.ByName(config.DC); dc == gpio.INVALID {
|
||||
return nil, fmt.Errorf("invalid dc pin %q", config.DC)
|
||||
}
|
||||
bits = 8
|
||||
}
|
||||
|
||||
port, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
c, err := port.Connect(3300*physic.KiloHertz, spi.Mode0, bits)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connecting on SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
return newDev(c, opts, true, dc)
|
||||
}
|
||||
|
||||
func (d *Dev) String() string {
|
||||
if d.spi {
|
||||
return fmt.Sprintf("ssd1360.Dev{%s, %s, %s}", d.c, d.dc, d.rect.Max)
|
||||
}
|
||||
return fmt.Sprintf("ssd1360.Dev{%s, %s}", d.c, d.rect.Max)
|
||||
}
|
||||
|
||||
// ColorModel implements display.Drawer.
|
||||
//
|
||||
// It is a one bit color model, as implemented by image1bit.Bit.
|
||||
func (d *Dev) ColorModel() color.Model {
|
||||
return image1bit.BitModel
|
||||
}
|
||||
|
||||
// Bounds implements display.Drawer. Min is guaranteed to be {0, 0}.
|
||||
func (d *Dev) Bounds() image.Rectangle {
|
||||
return d.rect
|
||||
}
|
||||
|
||||
// Draw implements display.Drawer.
|
||||
//
|
||||
// It draws synchronously, once this function returns, the display is updated.
|
||||
// It means that on slow bus (I²C), it may be preferable to defer Draw() calls
|
||||
// to a background goroutine.
|
||||
func (d *Dev) Draw(r image.Rectangle, src image.Image, sp image.Point) error {
|
||||
var next []byte
|
||||
if img, ok := src.(*image1bit.VerticalLSB); ok && r == d.rect && img.Rect == d.rect && sp.X == 0 && sp.Y == 0 {
|
||||
// Exact size, full frame, image1bit encoding: fast path!
|
||||
next = img.Pix
|
||||
} else {
|
||||
// Double buffering.
|
||||
if d.next == nil {
|
||||
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||
}
|
||||
next = d.next.Pix
|
||||
draw.Src.Draw(d.next, r, src, sp)
|
||||
}
|
||||
return d.drawInternal(next)
|
||||
}
|
||||
|
||||
// DrawImage implements display.imageDrawer.
|
||||
func (d *Dev) DrawImage(src image.Image) error {
|
||||
return d.Draw(d.Bounds(), src, image.Point{})
|
||||
}
|
||||
|
||||
// Write writes a buffer of pixels to the display.
|
||||
//
|
||||
// The format is unsual as each byte represent 8 vertical pixels at a time. The
|
||||
// format is horizontal bands of 8 pixels high.
|
||||
//
|
||||
// This function accepts the content of image1bit.VerticalLSB.Pix.
|
||||
func (d *Dev) Write(pixels []byte) (int, error) {
|
||||
if len(pixels) != len(d.buffer) {
|
||||
return 0, fmt.Errorf("ssd1306: invalid pixel stream length; expected %d bytes, got %d bytes", len(d.buffer), len(pixels))
|
||||
}
|
||||
// Write() skips d.next so it saves 1kb of RAM.
|
||||
if err := d.drawInternal(pixels); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(pixels), nil
|
||||
}
|
||||
|
||||
// Scroll scrolls an horizontal band.
|
||||
//
|
||||
// Only one scrolling operation can happen at a time.
|
||||
//
|
||||
// Both startLine and endLine must be multiples of 8.
|
||||
//
|
||||
// Use -1 for endLine to extend to the bottom of the display.
|
||||
func (d *Dev) Scroll(o Orientation, rate FrameRate, startLine, endLine int) error {
|
||||
h := d.rect.Dy()
|
||||
if endLine == -1 {
|
||||
endLine = h
|
||||
}
|
||||
if startLine >= endLine {
|
||||
return fmt.Errorf("startLine (%d) must be lower than endLine (%d)", startLine, endLine)
|
||||
}
|
||||
if startLine&7 != 0 || startLine < 0 || startLine >= h {
|
||||
return fmt.Errorf("invalid startLine %d", startLine)
|
||||
}
|
||||
if endLine&7 != 0 || endLine < 0 || endLine > h {
|
||||
return fmt.Errorf("invalid endLine %d", endLine)
|
||||
}
|
||||
|
||||
startPage := uint8(startLine / 8)
|
||||
endPage := uint8(endLine / 8)
|
||||
d.scrolled = true
|
||||
if o == Left || o == Right {
|
||||
// page 28
|
||||
// <op>, dummy, <start page>, <rate>, <end page>, <dummy>, <dummy>, <ENABLE>
|
||||
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x00, 0xFF, 0x2F})
|
||||
}
|
||||
// page 29
|
||||
// <op>, dummy, <start page>, <rate>, <end page>, <offset>, <ENABLE>
|
||||
// page 30: 0xA3 permits to set rows for scroll area.
|
||||
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x01, 0x2F})
|
||||
}
|
||||
|
||||
// StopScroll stops any scrolling previously set and resets the screen.
|
||||
func (d *Dev) StopScroll() error {
|
||||
return d.sendCommand([]byte{0x2E})
|
||||
}
|
||||
|
||||
// SetContrast changes the screen contrast.
|
||||
//
|
||||
// Note: values other than 0xff do not seem useful...
|
||||
func (d *Dev) SetContrast(level byte) error {
|
||||
return d.sendCommand([]byte{0x81, level})
|
||||
}
|
||||
|
||||
// SetDisplayStartLine causes the display to start from startLine, effectively
|
||||
// scrolling the screen to that position.
|
||||
//
|
||||
// startLine must be between 0 and 63.
|
||||
func (d *Dev) SetDisplayStartLine(startLine byte) error {
|
||||
if startLine > 63 {
|
||||
return fmt.Errorf("ssd1306: invalid startLine %d", startLine)
|
||||
}
|
||||
return d.sendCommand([]byte{_SETSTARTLINE | startLine})
|
||||
}
|
||||
|
||||
// Halt turns off the display.
|
||||
//
|
||||
// Sending any other command afterward reenables the display.
|
||||
func (d *Dev) Halt() error {
|
||||
d.halted = false
|
||||
err := d.sendCommand([]byte{0xAE})
|
||||
if err == nil {
|
||||
d.halted = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Invert the display (black on white vs white on black).
|
||||
func (d *Dev) Invert(blackOnWhite bool) error {
|
||||
b := []byte{0xA6}
|
||||
if blackOnWhite {
|
||||
b[0] = 0xA7
|
||||
}
|
||||
return d.sendCommand(b)
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
// newDev is the common initialization code that is independent of the
|
||||
// communication protocol (I²C or SPI) being used.
|
||||
func newDev(c conn.Conn, opts *Opts, usingSPI bool, dc gpio.PinOut) (*Dev, error) {
|
||||
if opts.W < 8 || opts.W > 128 || opts.W&7 != 0 {
|
||||
return nil, fmt.Errorf("ssd1306: invalid width %d", opts.W)
|
||||
}
|
||||
if opts.H < 8 || opts.H > 64 || opts.H&7 != 0 {
|
||||
return nil, fmt.Errorf("ssd1306: invalid height %d", opts.H)
|
||||
}
|
||||
|
||||
nbPages := opts.H / 8
|
||||
pageSize := opts.W
|
||||
d := &Dev{
|
||||
c: c,
|
||||
spi: usingSPI,
|
||||
dc: dc,
|
||||
rect: image.Rect(0, 0, opts.W, opts.H),
|
||||
buffer: make([]byte, nbPages*pageSize),
|
||||
startPage: 0,
|
||||
endPage: nbPages,
|
||||
startCol: 0,
|
||||
endCol: opts.W,
|
||||
// Signal that the screen must be redrawn on first draw().
|
||||
scrolled: true,
|
||||
}
|
||||
if err := d.sendCommand(getInitCmd(opts)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func getInitCmd(opts *Opts) []byte {
|
||||
// Set COM output scan direction; C0 means normal; C8 means reversed
|
||||
comScan := byte(0xC8)
|
||||
// See page 40.
|
||||
columnAddr := byte(0xA1)
|
||||
if opts.Rotated {
|
||||
// Change order both horizontally and vertically.
|
||||
comScan = 0xC0
|
||||
columnAddr = byte(0xA0)
|
||||
}
|
||||
if opts.MirrorVertical {
|
||||
comScan = byte(0xC0)
|
||||
}
|
||||
if opts.MirrorHorizontal {
|
||||
columnAddr = byte(0xA0)
|
||||
}
|
||||
// See page 40.
|
||||
hwLayout := byte(0x02)
|
||||
if !opts.Sequential {
|
||||
hwLayout |= 0x10
|
||||
}
|
||||
if opts.SwapTopBottom {
|
||||
hwLayout |= 0x20
|
||||
}
|
||||
// Set the max frequency. The problem with I²C is that it creates visible
|
||||
// tear down. On SPI at high speed this is not visible. Page 23 pictures how
|
||||
// to avoid tear down. For now default to max frequency.
|
||||
freq := byte(0xF0)
|
||||
|
||||
// Initialize the device by fully resetting all values.
|
||||
// Page 64 has the full recommended flow.
|
||||
// Page 28 lists all the commands.
|
||||
return []byte{
|
||||
0xAE, // Display off
|
||||
0xD3, 0x00, // Set display offset; 0
|
||||
0x40, // Start display start line; 0
|
||||
columnAddr, // Set segment remap; RESET is column 127.
|
||||
comScan, //
|
||||
0xDA, hwLayout, // Set COM pins hardware configuration; see page 40
|
||||
0x81, 0xFF, // Set max contrast
|
||||
0xA4, // Set display to use GDDRAM content
|
||||
0xA6, // Set normal display (0xA7 for inverted 0=lit, 1=dark)
|
||||
0xD5, freq, // Set osc frequency and divide ratio; power on reset value is 0x80.
|
||||
0x8D, 0x14, // Enable charge pump regulator; page 62
|
||||
0xD9, 0xF1, // Set pre-charge period; from adafruit driver
|
||||
0xDB, 0x40, // Set Vcomh deselect level; page 32
|
||||
0x2E, // Deactivate scroll
|
||||
0xA8, byte(opts.H - 1), // Set multiplex ratio (number of lines to display)
|
||||
0x20, 0x00, // Set memory addressing mode to horizontal
|
||||
0x21, 0, uint8(opts.W - 1), // Set column address (Width)
|
||||
0x22, 0, uint8(opts.H/8 - 1), // Set page address (Pages)
|
||||
0xAF, // Display on
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dev) calculateSubset(next []byte) (int, int, int, int, bool) {
|
||||
w := d.rect.Dx()
|
||||
h := d.rect.Dy()
|
||||
startPage := 0
|
||||
endPage := h / 8
|
||||
startCol := 0
|
||||
endCol := w
|
||||
if d.scrolled {
|
||||
// Painting disable scrolling but if scrolling was enabled, this requires a
|
||||
// full screen redraw.
|
||||
d.scrolled = false
|
||||
} else {
|
||||
// Calculate the smallest square that need to be sent.
|
||||
pageSize := w
|
||||
|
||||
// Top.
|
||||
for ; startPage < endPage; startPage++ {
|
||||
x := pageSize * startPage
|
||||
y := pageSize * (startPage + 1)
|
||||
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Bottom.
|
||||
for ; endPage > startPage; endPage-- {
|
||||
x := pageSize * (endPage - 1)
|
||||
y := pageSize * endPage
|
||||
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if startPage == endPage {
|
||||
// Early exit, the image is exactly the same.
|
||||
return 0, 0, 0, 0, true
|
||||
}
|
||||
|
||||
// Left.
|
||||
for ; startCol < endCol; startCol++ {
|
||||
for i := startPage; i < endPage; i++ {
|
||||
x := i*pageSize + startCol
|
||||
if d.buffer[x] != next[x] {
|
||||
goto breakLeft
|
||||
}
|
||||
}
|
||||
}
|
||||
breakLeft:
|
||||
|
||||
// Right.
|
||||
for ; endCol > startCol; endCol-- {
|
||||
for i := startPage; i < endPage; i++ {
|
||||
x := i*pageSize + endCol - 1
|
||||
if d.buffer[x] != next[x] {
|
||||
goto breakRight
|
||||
}
|
||||
}
|
||||
}
|
||||
breakRight:
|
||||
}
|
||||
return startPage, endPage, startCol, endCol, false
|
||||
}
|
||||
|
||||
// drawInternal sends image data to the controller.
|
||||
func (d *Dev) drawInternal(next []byte) error {
|
||||
startPage, endPage, startCol, endCol, skip := d.calculateSubset(next)
|
||||
if skip {
|
||||
return nil
|
||||
}
|
||||
copy(d.buffer, next)
|
||||
|
||||
if d.startPage != startPage || d.endPage != endPage || d.startCol != startCol || d.endCol != endCol {
|
||||
d.startPage = startPage
|
||||
d.endPage = endPage
|
||||
d.startCol = startCol
|
||||
d.endCol = endCol
|
||||
}
|
||||
|
||||
pageSize := d.rect.Dx()
|
||||
for page := d.startPage; page < d.endPage; page++ {
|
||||
err := d.sendCommand([]byte{
|
||||
_PAGESTARTADDRESS | byte(page),
|
||||
_SETLOWCOLUMN | (byte(d.startCol) & 0x0F),
|
||||
_SETHIGHCOLUMN | (byte(d.startCol) >> 4),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pageStart := page * pageSize
|
||||
err = d.sendData(d.buffer[pageStart+d.startCol : pageStart+d.endCol])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dev) sendData(c []byte) error {
|
||||
if d.halted {
|
||||
// Transparently enable the display.
|
||||
if err := d.sendCommand(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if d.spi {
|
||||
// 4-wire SPI.
|
||||
if err := d.dc.Out(gpio.High); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.c.Tx(c, nil)
|
||||
}
|
||||
return d.c.Tx(append([]byte{i2cData}, c...), nil)
|
||||
}
|
||||
|
||||
func (d *Dev) sendCommand(c []byte) error {
|
||||
if d.halted {
|
||||
// Transparently enable the display.
|
||||
c = append([]byte{0xAF}, c...)
|
||||
d.halted = false
|
||||
}
|
||||
if d.spi {
|
||||
if d.dc == nil {
|
||||
// 3-wire SPI.
|
||||
return errors.New("ssd1306: 3-wire SPI mode is not yet implemented")
|
||||
}
|
||||
// 4-wire SPI.
|
||||
if err := d.dc.Out(gpio.Low); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.c.Tx(c, nil)
|
||||
}
|
||||
return d.c.Tx(append([]byte{i2cCmd}, c...), nil)
|
||||
}
|
||||
|
||||
func (d *Dev) At(x, y int) color.Color {
|
||||
if d.next == nil {
|
||||
return pixel.Off
|
||||
}
|
||||
return d.next.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Dev) Set(x, y int, c color.Color) {
|
||||
if d.next == nil {
|
||||
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||
}
|
||||
d.next.Set(x, y, c)
|
||||
}
|
||||
|
||||
func (d *Dev) Refresh() error {
|
||||
if d.next == nil {
|
||||
return nil
|
||||
}
|
||||
return d.drawInternal(d.next.Pix)
|
||||
}
|
||||
|
||||
func (d *Dev) Size() image.Point {
|
||||
return d.rect.Max
|
||||
}
|
||||
|
||||
const (
|
||||
i2cCmd = 0x00 // I²C transaction has stream of command bytes
|
||||
i2cData = 0x40 // I²C transaction has stream of data bytes
|
||||
)
|
||||
Reference in new issue
Block a user