Skip to content

Instantly share code, notes, and snippets.

@nathan-osman
Created June 1, 2025 05:24
Show Gist options
  • Save nathan-osman/d92e35f8558469ab95cb82744a4013a4 to your computer and use it in GitHub Desktop.
Save nathan-osman/d92e35f8558469ab95cb82744a4013a4 to your computer and use it in GitHub Desktop.
Display a simple pattern on a SH1122 OLED display
package main
import (
"time"
"periph.io/x/conn/v3/gpio"
"periph.io/x/conn/v3/gpio/gpioreg"
"periph.io/x/conn/v3/physic"
"periph.io/x/conn/v3/spi"
"periph.io/x/conn/v3/spi/spireg"
"periph.io/x/host/v3"
)
const (
width = 256
height = 64
)
func main() {
// Initialize periph.io drivers
_, err := host.Init()
if err != nil {
panic(err)
}
// Open the SPI port
p, err := spireg.Open("/dev/spidev0.0")
if err != nil {
panic(err)
}
defer p.Close()
// Connect to SPI device
c, err := p.Connect(1*1024*1024*physic.Hertz, spi.Mode0, 8)
if err != nil {
panic(err)
}
var (
rstPin = gpioreg.ByName("GPIO25")
dcPin = gpioreg.ByName("GPIO24")
csPin = gpioreg.ByName("GPIO23")
)
// Reset sequence
if err := rstPin.Out(gpio.High); err != nil {
panic(err)
}
time.Sleep(10 * time.Millisecond)
if err := rstPin.Out(gpio.Low); err != nil {
panic(err)
}
time.Sleep(10 * time.Millisecond)
if err := rstPin.Out(gpio.High); err != nil {
panic(err)
}
// Setup dc and cs pins
if err := dcPin.Out(gpio.Low); err != nil {
panic(err)
}
if err := csPin.Out(gpio.High); err != nil {
panic(err)
}
// Send the provided data over the SPI connection
send := func(b []byte, data bool) error {
var l gpio.Level
if data {
l = gpio.High
} else {
l = gpio.Low
}
if err := dcPin.Out(l); err != nil {
return err
}
if err := csPin.Out(gpio.Low); err != nil {
return err
}
if err := c.Tx(b, make([]byte, len(b))); err != nil {
return err
}
return csPin.Out(gpio.High)
}
// Turn the display on
if err := send([]byte{0xaf}, false); err != nil {
panic(err)
}
// Build the pattern
b := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}
for i := 0; i < 9; i++ {
b = append(b, b...)
}
// Send the pattern twice
for i := 0; i < 2; i++ {
if err := send(b, true); err != nil {
panic(err)
}
}
time.Sleep(1 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment