Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Last active February 22, 2026 22:44
Show Gist options
  • Select an option

  • Save akhenakh/c077a0fb30463838b3edbd3fba2e5a0a to your computer and use it in GitHub Desktop.

Select an option

Save akhenakh/c077a0fb30463838b3edbd3fba2e5a0a to your computer and use it in GitHub Desktop.
CS816 Tinygo
package main
import (
"fmt"
"image/color"
"machine"
"time"
"tinygo.org/x/drivers/st7789"
)
// --- CST816S/D Touch Driver ---
const cst816Address = 0x15
const (
RegFingerNum = 0x02
RegXposH = 0x03
RegIrqPluseWidth = 0xED
RegNorScanPer = 0xEE
RegIrqCtl = 0xFA
RegDisAutoSleep = 0xFE
)
type CST816 struct {
bus *machine.I2C
rst machine.Pin
int machine.Pin
}
func NewCST816(bus *machine.I2C, rst, intPin machine.Pin) *CST816 {
return &CST816{bus: bus, rst: rst, int: intPin}
}
func (d *CST816) Configure() error {
d.rst.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.int.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
// Hardware Reset
d.rst.Low()
time.Sleep(100 * time.Millisecond)
d.rst.High()
time.Sleep(100 * time.Millisecond)
// Wake up / Stop Auto Sleep
d.bus.Tx(cst816Address, []byte{RegDisAutoSleep, 0x01}, nil)
// Enable Point Mode (Continuous coordinate reporting)
d.bus.Tx(cst816Address, []byte{RegIrqCtl, 0x41}, nil)
d.bus.Tx(cst816Address, []byte{RegIrqPluseWidth, 0x01}, nil)
d.bus.Tx(cst816Address, []byte{RegNorScanPer, 0x01}, nil)
return nil
}
// Read returns X, Y coordinates and a boolean indicating if touched.
func (d *CST816) Read() (int16, int16, bool) {
data := make([]byte, 5)
// Read starting from FingerNum (0x02) to YposL (0x06)
err := d.bus.Tx(cst816Address, []byte{RegFingerNum}, data)
if err != nil || data[0] == 0 {
return 0, 0, false
}
// Cast the byte to int16 *before* shifting left by 8
rawX := (int16(data[1]&0x0F) << 8) | int16(data[2])
rawY := (int16(data[3]&0x0F) << 8) | int16(data[4])
// Match the hardware orientation
x := rawY
y := 240 - rawX
return x, y, true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment