Compare commits

..

4 Commits

Author SHA1 Message Date
deadprogram 85e123eeb2 st7789: work in progress on display refactor
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-12-20 10:29:55 +01:00
deadprogram 51561d4eab st7789: add Bus interface to accomodate both SPI and parallel connections to display
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-12-20 10:29:55 +01:00
deadprogram b561dc36f2 examples: switch st7789 example to use the Adafruit Clue since that device actually comes with one.
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-12-20 10:29:55 +01:00
deadprogram 85b24b3418 st7789: remove dependency on the machine package by using internal/pin instead
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-12-20 10:29:55 +01:00
45 changed files with 1091 additions and 4261 deletions
-1
View File
@@ -1,3 +1,2 @@
# These are supported funding model platforms
open_collective: tinygo
-37
View File
@@ -1,40 +1,3 @@
0.35.0
---
- **new devices**
- **unoqmatrix**
- LED matrix on the Arduino Uno Q
- **waveshare-epd (ssd1680)**
- Add driver for Waveshare 2.9 inch v2 e-paper display
- **enhancements**
- **gps**
- add UBX config command support (#831)
- improve implementation for UBX config commands
- revamp validSentence() to avoid heap allocation for errors
- export some errors for checking/suppression from client
- improvements and corrections for config commands
- **lora**
- fill out more constants for lora device
- **mcp2515**
- add support for extended CAN IDs (#857)
- **si5351**
- complete refactor for more complete interface
- **st7735**
- remove dependency on the machine package
- **sx127x**
- add functions used for FSK radio communication
- **ws2812**
- add brightness control
- add PIO support for RP2040/RP2350
- **bugfixes**
- **st7789**
- fix scroll on rotated displays
- fix driver when rotated 90º
- **ws2812**
- fix brightness control issues (#858)
0.34.0
---
- **core**
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright The TinyGo Authors. All rights reserved.
Copyright (c) 2018-2025 The TinyGo Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
-14
View File
@@ -26,17 +26,3 @@ unit-test:
@go test -v $(addprefix ./,$(TESTS))
test: clean fmt-check unit-test smoke-test
EXCLUDE_DIRS = build cmd examples internal lora ndir netdev netlink tester
drivers-count:
@root_count=$$(find . -mindepth 1 -maxdepth 1 -type d | grep -vE '^\./($(subst $(space),|,$(EXCLUDE_DIRS)))$$' | wc -l); \
epd_count=$$(find ./waveshare-epd -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l); \
total=$$((root_count + epd_count)); \
echo "Total drivers: $$total (root: $$root_count, waveshare-epd: $$epd_count)"
drivers-list:
@{ \
find . -mindepth 1 -maxdepth 1 -type d | grep -vE '^\./($(subst $(space),|,$(EXCLUDE_DIRS)))$$'; \
if [ -d ./waveshare-epd ]; then find ./waveshare-epd -mindepth 1 -maxdepth 1 -type d; fi; \
} | sed 's|^\./||' | sort
+1 -4
View File
@@ -3,14 +3,11 @@
[![PkgGoDev](https://pkg.go.dev/badge/tinygo.org/x/drivers)](https://pkg.go.dev/tinygo.org/x/drivers) [![Build](https://github.com/tinygo-org/drivers/actions/workflows/build.yml/badge.svg?branch=dev)](https://github.com/tinygo-org/drivers/actions/workflows/build.yml)
This package provides a collection of over 140 different hardware drivers for devices such as sensors, displays, wireless adaptors, and actuators, that can be used together with [TinyGo](https://tinygo.org).
This package provides a collection of over 130 different hardware drivers for devices such as sensors, displays, wireless adaptors, and actuators, that can be used together with [TinyGo](https://tinygo.org).
For the complete list, please see:
https://tinygo.org/docs/reference/devices/
> [!IMPORTANT]
> You can help TinyGo with a financial contribution using OpenCollective. Please see https://opencollective.com/tinygo for more information. Thank you!
## Installing
```shell
+6 -18
View File
@@ -8,6 +8,7 @@ import (
)
func main() {
println("GPS UART Example")
machine.UART1.Configure(machine.UARTConfig{BaudRate: 9600})
ublox := gps.NewUART(machine.UART1)
parser := gps.NewParser()
@@ -15,24 +16,14 @@ func main() {
for {
s, err := ublox.NextSentence()
if err != nil {
switch err {
case gps.ErrUnknownNMEASentence, gps.ErrInvalidNMEASentence, gps.ErrInvalidNMEASentenceLength:
continue
default:
println("sentence error:", err)
continue
}
println(err)
continue
}
fix, err = parser.Parse(s)
if err != nil {
switch err {
case gps.ErrUnknownNMEASentence, gps.ErrInvalidNMEASentence, gps.ErrInvalidNMEASentenceLength:
continue
default:
println("parse error:", err)
continue
}
println(err)
continue
}
if fix.Valid {
print(fix.Time.Format("15:04:05"))
@@ -52,10 +43,7 @@ func main() {
}
println()
} else {
if fix.Type == gps.GSV {
// GSV sentence provides satellite count even if no fix yet
println(fix.Satellites, "satellites visible")
}
println("No fix")
}
time.Sleep(200 * time.Millisecond)
}
+1 -1
View File
@@ -21,7 +21,7 @@ func main() {
SDI: machine.SPI0_SDI_PIN,
Mode: 0})
can := mcp2515.New(spi, csPin)
can.Configure(mcp2515.Configuration{})
can.Configure()
err := can.Begin(mcp2515.CAN500kBps, mcp2515.Clock8MHz)
if err != nil {
failMessage(err.Error())
+65 -33
View File
@@ -29,60 +29,92 @@ func main() {
// Create driver instance
clockgen := si5351.New(machine.I2C0)
// Initialize device
cnf := si5351.Config{
Capacitance: si5351.CrystalLoad10PF,
// Verify device wired properly
connected, err := clockgen.Connected()
if err != nil {
println("Unable to read device status")
time.Sleep(time.Second)
}
if !connected {
for {
println("Unable to detect si5351 device")
time.Sleep(time.Second)
}
}
if err := clockgen.Configure(cnf); err != nil {
println("Failed to configure Si5351:", err.Error())
return
}
println("Si5351 configured")
// Initialise device
clockgen.Configure()
// Now configure the clock outputs.
clockgen.SetFrequency(si5351.Clock0, 112_500_000)
// Now configue the PLLs and clock outputs.
// The PLLs can be configured with a multiplier and division of the on-board
// 25mhz reference crystal. For example configure PLL A to 900mhz by multiplying
// by 36. This uses an integer multiplier which is more accurate over time
// but allows less of a range of frequencies compared to a fractional
// multiplier shown next.
clockgen.ConfigurePLL(si5351.PLL_A, 36, 0, 1) // Multiply 25mhz by 36
println("PLL A frequency: 900mhz")
// And next configure PLL B to 616.6667mhz by multiplying 25mhz by 24.667 using
// the fractional multiplier configuration. Notice you specify the integer
// multiplier and then a numerator and denominator as separate values, i.e.
// numerator 2 and denominator 3 means 2/3 or 0.667. This fractional
// configuration is susceptible to some jitter over time but can set a larger
// range of frequencies.
clockgen.ConfigurePLL(si5351.PLL_B, 24, 2, 3) // Multiply 25mhz by 24.667 (24 2/3)
println("PLL B frequency: 616.6667mhz")
// Now configure the clock outputs. Each is driven by a PLL frequency as input
// and then further divides that down to a specific frequency.
// Configure clock 0 output to be driven by PLL A divided by 8, so an output
// of 112.5mhz (900mhz / 8). Again this uses the most precise integer division
// but can't set as wide a range of values.
clockgen.ConfigureMultisynth(0, si5351.PLL_A, 8, 0, 1) // Divide by 8 (8 0/1)
println("Clock 0: 112.5mhz")
// Next configure clock 1 for 13.5531mhz (616.6667mhz / 45.5).
// This uses fractional division.
clockgen.SetFrequency(si5351.Clock1, 13_553_125)
// Next configure clock 1 to be driven by PLL B divided by 45.5 to get
// 13.5531mhz (616.6667mhz / 45.5). This uses fractional division and again
// notice the numerator and denominator are explicitly specified. This is less
// precise but allows a large range of frequencies.
clockgen.ConfigureMultisynth(1, si5351.PLL_B, 45, 1, 2) // Divide by 45.5 (45 1/2)
println("Clock 1: 13.5531mhz")
// Finally configure clock 2 to output of 10.706khz.
clockgen.SetFrequency(si5351.Clock2, 10_706)
// Finally configure clock 2 to be driven by PLL B divided once by 900 to get
// down to 685.15 khz and then further divided by a special R divider that
// divides 685.15 khz by 64 to get a final output of 10.706khz.
clockgen.ConfigureMultisynth(2, si5351.PLL_B, 900, 0, 1) // Divide by 900 (900 0/1)
// Set the R divider, this can be a value of:
// - R_DIV_1: divider of 1
// - R_DIV_2: divider of 2
// - R_DIV_4: divider of 4
// - R_DIV_8: divider of 8
// - R_DIV_16: divider of 16
// - R_DIV_32: divider of 32
// - R_DIV_64: divider of 64
// - R_DIV_128: divider of 128
clockgen.ConfigureRdiv(2, si5351.R_DIV_64)
println("Clock 2: 10.706khz")
// After configuring the clocks enable the outputs.
clockgen.EnableOutput(si5351.Clock0, true)
clockgen.EnableOutput(si5351.Clock1, true)
clockgen.EnableOutput(si5351.Clock2, true)
println("All outputs enabled")
// After configuring PLLs and clocks, enable the outputs.
clockgen.EnableOutputs()
time.Sleep(time.Second)
clockgen.EnableOutput(si5351.Clock0, false)
clockgen.EnableOutput(si5351.Clock1, false)
clockgen.EnableOutput(si5351.Clock2, false)
clockgen.DisableOutputs()
println("All outputs disabled for 5 seconds")
time.Sleep(5 * time.Second)
// Now turn clock outputs on and off repeatedly
// Now use SetFrequency to re-set the frequencies of the outputs
on := false
for {
if on {
println("Setting clock outputs off")
clockgen.EnableOutput(si5351.Clock0, false)
clockgen.EnableOutput(si5351.Clock1, false)
clockgen.EnableOutput(si5351.Clock2, false)
println("Setting Clock 0 output off")
clockgen.OutputEnable(0, false)
on = false
} else {
println("Setting clock outputs on")
clockgen.EnableOutput(si5351.Clock0, true)
clockgen.EnableOutput(si5351.Clock1, true)
clockgen.EnableOutput(si5351.Clock2, true)
println("Setting Clock 0 output to 100mhz")
clockgen.SetFrequency(100*machine.MHz, 0, si5351.PLL_A)
on = true
}
time.Sleep(1 * time.Second)
time.Sleep(5 * time.Second)
}
}
+4 -4
View File
@@ -29,10 +29,10 @@ func main() {
Mode: 0,
})
display := st7789.New(machine.SPI0,
machine.P6, // TFT_RESET
machine.P7, // TFT_DC
machine.P8, // TFT_CS
machine.P9) // TFT_LITE
machine.TFT_RESET, // TFT_RESET
machine.TFT_DC, // TFT_DC
machine.TFT_CS, // TFT_CS
machine.TFT_LITE) // TFT_LITE
display.Configure(st7789.Config{
Rotation: st7789.NO_ROTATION,
-54
View File
@@ -1,54 +0,0 @@
package main
import (
"machine"
"image/color"
"math/rand"
"tinygo.org/x/drivers/unoqmatrix"
)
var on = color.RGBA{255, 255, 255, 255}
func main() {
display := unoqmatrix.NewFromBasePin(machine.PF0)
display.ClearDisplay()
w, h := display.Size()
x := int16(0)
y := int16(0)
deltaX := int16(1)
deltaY := int16(1)
for {
pixel := display.GetPixel(x, y)
if pixel.R != 0 || pixel.G != 0 || pixel.B != 0 {
display.ClearDisplay()
x = 1 + int16(rand.Int31n(3))
y = 1 + int16(rand.Int31n(3))
deltaX = 1
deltaY = 1
if rand.Int31n(2) == 0 {
deltaX = -1
}
if rand.Int31n(2) == 0 {
deltaY = -1
}
}
display.SetPixel(x, y, on)
x += deltaX
y += deltaY
if x == 0 || x == w-1 {
deltaX = -deltaX
}
if y == 0 || y == h-1 {
deltaY = -deltaY
}
display.Display()
}
}
-137
View File
@@ -1,137 +0,0 @@
package main
import (
"image/color"
"machine"
"time"
"tinygo.org/x/drivers/waveshare-epd/epd2in9v2"
)
var display epd2in9v2.Device
func main() {
machine.SPI0.Configure(machine.SPIConfig{
Frequency: 12000000,
SCK: machine.EPD_SCK_PIN,
SDO: machine.EPD_SDO_PIN,
})
display = epd2in9v2.New(
machine.SPI0,
machine.EPD_CS_PIN,
machine.EPD_DC_PIN,
machine.EPD_RESET_PIN,
machine.EPD_BUSY_PIN,
)
display.Configure(epd2in9v2.Config{
Rotation: epd2in9v2.ROTATION_270,
Speed: epd2in9v2.SPEED_DEFAULT,
Blocking: true,
})
black := color.RGBA{0, 0, 0, 255}
white := color.RGBA{255, 255, 255, 255}
// --- Step 1: clear to white ---
println("epd2in9v2: clearing display")
display.ClearBuffer()
display.Display()
time.Sleep(2 * time.Second)
// --- Step 2: full refresh checkerboard ---
println("epd2in9v2: drawing checkerboard (full refresh)")
w, h := display.Size()
for i := int16(0); i < w/8; i++ {
for j := int16(0); j < h/8; j++ {
if (i+j)%2 == 0 {
fillRect(i*8, j*8, 8, 8, black)
}
}
}
display.Display()
time.Sleep(2 * time.Second)
// --- Step 3: fast refresh - draw border and diagonal cross ---
println("epd2in9v2: switching to fast refresh")
display.SetSpeed(epd2in9v2.SPEED_FAST)
display.ClearBuffer()
for x := int16(0); x < w; x++ {
display.SetPixel(x, 0, black)
display.SetPixel(x, h-1, black)
}
for y := int16(0); y < h; y++ {
display.SetPixel(0, y, black)
display.SetPixel(w-1, y, black)
}
for i := int16(0); i < w && i < h; i++ {
display.SetPixel(i, i*h/w, black)
display.SetPixel(w-1-i, i*h/w, black)
}
display.Display()
time.Sleep(2 * time.Second)
// --- Step 4: partial refresh counter ---
println("epd2in9v2: partial refresh demo")
display.SetSpeed(epd2in9v2.SPEED_DEFAULT)
display.ClearBuffer()
println("epd2in9v2: setting base image")
display.DisplayWithBase()
for count := 0; count < 10; count++ {
cx := int16(120)
cy := int16(50)
fillRect(cx, cy, 60, 20, white)
digit := int16(count % 10)
drawDigit(cx+22, cy+2, digit, black)
display.DisplayPartial()
time.Sleep(500 * time.Millisecond)
}
time.Sleep(2 * time.Second)
// --- Step 5: sleep ---
println("epd2in9v2: entering deep sleep")
display.ClearBuffer()
display.Display()
display.Sleep()
println("epd2in9v2: done, you can remove power")
}
func fillRect(x, y, w, h int16, c color.RGBA) {
for i := x; i < x+w; i++ {
for j := y; j < y+h; j++ {
display.SetPixel(i, j, c)
}
}
}
// drawDigit draws a simple 3x5-pixel-block digit (each block 4x3 px) at position (x,y).
func drawDigit(x, y, digit int16, c color.RGBA) {
segments := [10][5]uint8{
{0x7, 0x5, 0x5, 0x5, 0x7}, // 0
{0x2, 0x2, 0x2, 0x2, 0x2}, // 1
{0x7, 0x1, 0x7, 0x4, 0x7}, // 2
{0x7, 0x1, 0x7, 0x1, 0x7}, // 3
{0x5, 0x5, 0x7, 0x1, 0x1}, // 4
{0x7, 0x4, 0x7, 0x1, 0x7}, // 5
{0x7, 0x4, 0x7, 0x5, 0x7}, // 6
{0x7, 0x1, 0x1, 0x1, 0x1}, // 7
{0x7, 0x5, 0x7, 0x5, 0x7}, // 8
{0x7, 0x5, 0x7, 0x1, 0x7}, // 9
}
if digit < 0 || digit > 9 {
return
}
for row := int16(0); row < 5; row++ {
for col := int16(0); col < 3; col++ {
if segments[digit][row]&(0x4>>uint(col)) != 0 {
fillRect(x+col*4, y+row*3, 4, 3, c)
}
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build arduino || arduino_uno
//go:build arduino
package main
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !digispark && !arduino && !arduino_uno
//go:build !digispark && !arduino
package main
+2 -1
View File
@@ -1,16 +1,17 @@
module tinygo.org/x/drivers
go 1.22.1
toolchain go1.23.1
require (
github.com/eclipse/paho.mqtt.golang v1.2.0
github.com/frankban/quicktest v1.10.2
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/orsinium-labs/tinymath v1.1.0
github.com/soypat/natiu-mqtt v0.5.1
github.com/tinygo-org/pio v0.3.0
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d
golang.org/x/net v0.33.0
tinygo.org/x/tinyfont v0.3.0
-2
View File
@@ -17,8 +17,6 @@ github.com/orsinium-labs/tinymath v1.1.0 h1:KomdsyLHB7vE3f1nRAJF2dyf1m/gnM2HxfTe
github.com/orsinium-labs/tinymath v1.1.0/go.mod h1:WPXX6ei3KSXG7JfA03a+ekCYaY9SWN4I+JRl2p6ck+A=
github.com/soypat/natiu-mqtt v0.5.1 h1:rwaDmlvjzD2+3MCOjMZc4QEkDkNwDzbct2TJbpz+TPc=
github.com/soypat/natiu-mqtt v0.5.1/go.mod h1:xEta+cwop9izVCW7xOx2W+ct9PRMqr0gNVkvBPnQTc4=
github.com/tinygo-org/pio v0.3.0 h1:opEnOtw58KGB4RJD3/n/Rd0/djYGX3DeJiXLI6y/yDI=
github.com/tinygo-org/pio v0.3.0/go.mod h1:wf6c6lKZp+pQOzKKcpzchmRuhiMc27ABRuo7KVnaMFU=
github.com/valyala/fastjson v1.6.3/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d h1:0olWaB5pg3+oychR51GUVCEsGkeCU/2JxjBgIo4f3M0=
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c=
+34 -11
View File
@@ -11,18 +11,37 @@ import (
)
var (
ErrInvalidNMEASentenceLength = errors.New("invalid NMEA sentence length")
ErrInvalidNMEASentence = errors.New("invalid NMEA sentence format")
ErrEmptyNMEASentence = errors.New("cannot parse empty NMEA sentence")
ErrUnknownNMEASentence = errors.New("unsupported NMEA sentence type")
errInvalidGSVSentence = errors.New("invalid GSV NMEA sentence")
errInvalidNMEASentenceLength = errors.New("invalid NMEA sentence length")
errInvalidNMEAChecksum = errors.New("invalid NMEA sentence checksum")
errEmptyNMEASentence = errors.New("cannot parse empty NMEA sentence")
errUnknownNMEASentence = errors.New("unsupported NMEA sentence type")
errInvalidGGASentence = errors.New("invalid GGA NMEA sentence")
errInvalidRMCSentence = errors.New("invalid RMC NMEA sentence")
errInvalidGLLSentence = errors.New("invalid GLL NMEA sentence")
errGPSCommandRejected = errors.New("GPS command rejected (NAK)")
errNoACKToGPSCommand = errors.New("no ACK to GPS command")
)
type GPSError struct {
Err error
Info string
Sentence string
}
func newGPSError(err error, sentence string, info string) GPSError {
return GPSError{
Info: info,
Err: err,
Sentence: sentence,
}
}
func (ge GPSError) Error() string {
return ge.Err.Error() + " " + ge.Info + " " + ge.Sentence
}
func (ge GPSError) Unwrap() error {
return ge.Err
}
const (
minimumNMEALength = 7
startingDelimiter = '$'
@@ -31,18 +50,19 @@ const (
// Device wraps a connection to a GPS device.
type Device struct {
buffer []byte
bufIdx int
sentence strings.Builder
uart drivers.UART
bus drivers.I2C
address uint16
buffer [bufferSize]byte
}
// NewUART creates a new UART GPS connection. The UART must already be configured.
func NewUART(uart drivers.UART) Device {
return Device{
uart: uart,
buffer: make([]byte, bufferSize),
bufIdx: bufferSize,
sentence: strings.Builder{},
}
@@ -59,6 +79,7 @@ func NewI2CWithAddress(bus drivers.I2C, i2cAddress uint16) Device {
return Device{
bus: bus,
address: i2cAddress,
buffer: make([]byte, bufferSize),
bufIdx: bufferSize,
sentence: strings.Builder{},
}
@@ -151,15 +172,17 @@ func (gps *Device) WriteBytes(bytes []byte) {
// It has to end with a '*' character following by a checksum.
func validSentence(sentence string) error {
if len(sentence) < minimumNMEALength || sentence[0] != startingDelimiter || sentence[len(sentence)-3] != checksumDelimiter {
return ErrInvalidNMEASentenceLength
return errInvalidNMEASentenceLength
}
var cs byte = 0
for i := 1; i < len(sentence)-3; i++ {
cs ^= sentence[i]
}
checksum := strings.ToUpper(hex.EncodeToString([]byte{cs}))
if checksum != sentence[len(sentence)-2:] {
return ErrInvalidNMEASentence
if checksum != sentence[len(sentence)-2:len(sentence)] {
return newGPSError(errInvalidNMEAChecksum, sentence,
"expected "+sentence[len(sentence)-2:len(sentence)]+
" got "+checksum)
}
return nil
+3 -39
View File
@@ -6,28 +6,12 @@ import (
"time"
)
type NMEASentenceType string
const (
GSA NMEASentenceType = "GSA"
GGA NMEASentenceType = "GGA"
GLL NMEASentenceType = "GLL"
GSV NMEASentenceType = "GSV"
RMC NMEASentenceType = "RMC"
VTG NMEASentenceType = "VTG"
ZDA NMEASentenceType = "ZDA"
TXT NMEASentenceType = "TXT"
)
// Parser for GPS NMEA sentences.
type Parser struct {
}
// Fix is a GPS location fix
type Fix struct {
// Type is the NMEA sentence type that provided this fix.
Type NMEASentenceType
// Valid if the fix was valid.
Valid bool
@@ -62,30 +46,13 @@ func NewParser() Parser {
func (parser *Parser) Parse(sentence string) (Fix, error) {
var fix Fix
if sentence == "" {
return fix, ErrEmptyNMEASentence
return fix, errEmptyNMEASentence
}
if len(sentence) < 6 {
return fix, ErrInvalidNMEASentenceLength
return fix, errInvalidNMEASentenceLength
}
typ := sentence[3:6]
switch typ {
case "GSV":
// https://docs.novatel.com/OEM7/Content/Logs/GPGSV.htm
fields := strings.Split(sentence, ",")
// GSV sentences have at least 4 fields, but typically 8, 12, 16, or 20 depending on satellites in view
if len(fields) < 4 {
return fix, errInvalidGSVSentence
}
fix.Type = GSV
// Number of satellites in view is always field 3
fix.Satellites = findSatellites(fields[3])
// GSV does not provide position, time, or fix validity
fix.Valid = false
return fix, nil
case "GGA":
// https://docs.novatel.com/OEM7/Content/Logs/GPGGA.htm
fields := strings.Split(sentence, ",")
@@ -93,7 +60,6 @@ func (parser *Parser) Parse(sentence string) (Fix, error) {
return fix, errInvalidGGASentence
}
fix.Type = GGA
fix.Time = findTime(fields[1])
fix.Latitude = findLatitude(fields[2], fields[3])
fix.Longitude = findLongitude(fields[4], fields[5])
@@ -109,7 +75,6 @@ func (parser *Parser) Parse(sentence string) (Fix, error) {
return fix, errInvalidGLLSentence
}
fix.Type = GLL
fix.Latitude = findLatitude(fields[1], fields[2])
fix.Longitude = findLongitude(fields[3], fields[4])
fix.Time = findTime(fields[5])
@@ -124,7 +89,6 @@ func (parser *Parser) Parse(sentence string) (Fix, error) {
return fix, errInvalidRMCSentence
}
fix.Type = RMC
fix.Time = findTime(fields[1])
fix.Valid = (fields[2] == "A")
fix.Latitude = findLatitude(fields[3], fields[4])
@@ -140,7 +104,7 @@ func (parser *Parser) Parse(sentence string) (Fix, error) {
return fix, nil
}
return fix, ErrUnknownNMEASentence
return fix, newGPSError(errUnknownNMEASentence, sentence, typ)
}
// findTime returns the time from an NMEA sentence:
+2 -18
View File
@@ -8,29 +8,13 @@ import (
)
func TestParseUnknownSentence(t *testing.T) {
p := NewParser()
val := "$GPVTG,89.68,T,,M,0.00,N,0.0,K*5F"
_, err := p.Parse(val)
if err == nil {
t.Error("should have unknown sentence err")
}
}
func TestParseGSV(t *testing.T) {
c := qt.New(t)
p := NewParser()
val := "$GPGSV,3,1,09,07,14,317,22,08,31,284,25,10,32,133,39,16,85,232,29*7F"
fix, err := p.Parse(val)
if err != nil {
t.Error("should have parsed")
}
c.Assert(fix.Type, qt.Equals, GSV)
c.Assert(fix.Satellites, qt.Equals, int16(9))
c.Assert(fix.Valid, qt.Equals, false)
_, err := p.Parse(val)
c.Assert(err.Error(), qt.Contains, "unsupported NMEA sentence type")
}
func TestParseGGA(t *testing.T) {
+39 -240
View File
@@ -1,254 +1,53 @@
package gps
import (
"errors"
"time"
)
// FlightModeCmd is a UBX-CFG-NAV5 command
var nav5Cmd = CfgNav5{
Mask: CfgNav5Dyn | CfgNav5MinEl | CfgNav5PosFixMode,
DynModel: DynModeAirborne1g, // Airborne with <1g acceleration
FixMode: FixModeAuto, // Auto 2D/3D
MinElev_deg: 5, // Minimum elevation 5 degrees
FixedAlt_me2: 0, // Not used
FixedAltVar_m2e4: 0, // Not used
PDop: 100, // 10.0
TDop: 100, // 10.0
PAcc_m: 5000, // 5 meters
TAcc_m: 5000, // 5 meters
StaticHoldThresh_cm_s: 0, // Not used
DgnssTimeout_s: 0, // Not used
CnoThreshNumSVs: 0, // Not used
CnoThresh_dbhz: 0, // Not used
StaticHoldMaxDist_m: 0, // Not used
UtcStandard: 0, // Automatic
Reserved1: [2]byte{},
Reserved2: [5]byte{},
// flight mode disables the GPS COCOM limits
var flight_mode_cmd = [...]byte{
0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00,
0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00,
0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x16, 0xDC}
// Sets CFG-GNSS to disable everything other than GPS GNSS
// solution. Failure to do this means GPS power saving
// doesn't work. Not needed for MAX7, needed for MAX8's
var cfg_gnss_cmd = [...]byte{
0xB5, 0x62, 0x06, 0x3E, 0x2C, 0x00, 0x00, 0x00,
0x20, 0x05, 0x00, 0x08, 0x10, 0x00, 0x01, 0x00,
0x01, 0x01, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00,
0x01, 0x01, 0x03, 0x08, 0x10, 0x00, 0x00, 0x00,
0x01, 0x01, 0x05, 0x00, 0x03, 0x00, 0x00, 0x00,
0x01, 0x01, 0x06, 0x08, 0x0E, 0x00, 0x00, 0x00,
0x01, 0x01, 0xFC, 0x11}
func FlightMode(d Device) (err error) {
err = sendCommand(d, flight_mode_cmd[:])
return err
}
// SetFlightMode sends UBX-CFG-NAV5 command to set GPS into flight mode
func (d *Device) SetFlightMode() (err error) {
nav5Cmd.DynModel = DynModeAirborne1g
nav5Cmd.FixMode = FixModeAuto
nav5Cmd.Put42Bytes(d.buffer[:])
return d.SendCommand(d.buffer[:42])
func SetCfgGNSS(d Device) (err error) {
err = sendCommand(d, cfg_gnss_cmd[:])
return err
}
// SetPedestrianMode sends UBX-CFG-NAV5 command to set GPS into pedestrian mode
func (d *Device) SetPedestrianMode() (err error) {
nav5Cmd.DynModel = DynModePedestrian
nav5Cmd.FixMode = FixModeAuto
nav5Cmd.Put42Bytes(d.buffer[:])
return d.SendCommand(d.buffer[:42])
}
// SetAutomotiveMode sends UBX-CFG-NAV5 command to set GPS into automotive mode
func (d *Device) SetAutomotiveMode() (err error) {
nav5Cmd.DynModel = DynModeAutomotive
nav5Cmd.FixMode = FixModeAuto
nav5Cmd.Put42Bytes(d.buffer[:])
return d.SendCommand(d.buffer[:42])
}
// SetBikeMode sends UBX-CFG-NAV5 command to set GPS into bike mode
func (d *Device) SetBikeMode() (err error) {
nav5Cmd.DynModel = DynModeBike
nav5Cmd.FixMode = FixModeAuto
nav5Cmd.Put42Bytes(d.buffer[:])
return d.SendCommand(d.buffer[:42])
}
var (
// GGA (time, lat/lng, altitude)
messageRateGGACmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x00,
Rate: 1, // Every position fix
}
// GLL (time, lat/lng)
messageRateGLLCmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x01,
Rate: 1, // Every position fix
}
// GSA (satellite id list)
messageRateGSACmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x02,
Rate: 0, // Disabled
}
// GSV (satellite locations)
messageRateGSVCmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x03,
Rate: 0, // Every position fix
}
// RMC (time, lat/lng, speed, course)
messageRateRMCCmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x04,
Rate: 1, // Every position fix
}
// VTG (speed, course)
messageRateVTGCmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x05,
Rate: 0, // Disabled
}
// ZDA (time, timezone)
messageRateZDACmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x08,
Rate: 0, // Disabled
}
// TXT (text transmission)
messageRateTXTCmd = CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x41,
Rate: 0, // Disabled
}
)
// SetMessageRatesMinimal configures the GPS to output a minimal set of NMEA sentences:
// GSV, GGA, GLL, and RMC only.
func SetMessageRatesMinimal(d *Device) (err error) {
commands := []CfgMsg1{
messageRateGSACmd,
messageRateGLLCmd,
messageRateVTGCmd,
messageRateZDACmd,
messageRateTXTCmd,
}
for i := range commands {
commands[i].Rate = 0 // Disable
}
return setCfg1s(d, commands)
}
// SetMessageRatesAllEnabled configures the GPS to output all NMEA sentences
func SetMessageRatesAllEnabled(d *Device) (err error) {
commands := []CfgMsg1{
messageRateGSACmd,
messageRateGGACmd,
messageRateGLLCmd,
messageRateGSVCmd,
messageRateRMCCmd,
messageRateVTGCmd,
messageRateZDACmd,
messageRateTXTCmd,
}
for i := range commands {
commands[i].Rate = 1 // Enable
}
return setCfg1s(d, commands)
}
func setCfg1s(d *Device, commands []CfgMsg1) (err error) {
var buf [9]byte
for _, cmd := range commands {
cmd.Put9Bytes(buf[:])
// TODO handle errors differently here?
// This implementation just saves the last error and continues.
// Due to the GPS modules sending updates asynchronously
// the response is interleaved along with regular ASCII
// NMEA messages.
err = d.SendCommand(buf[:])
time.Sleep(100 * time.Millisecond)
}
return
}
// gnssDisableCmd is a UBX-CFG-GNSS command to disable all GNSS but GPS
// Needed for MAX8's, not needed for MAX7
var gnssDisableCmd = CfgGnss{
MsgVer: 0x00,
NumTrkChHw: 0x20, // 32 channels
NumTrkChUse: 0x20,
ConfigBlocks: []CfgGnssConfigBlocksType{
{GnssId: 0, ResTrkCh: 8, MaxTrkCh: 16, Flags: CfgGnssEnable | 0x010000}, // GPS enabled
{GnssId: 1, ResTrkCh: 1, MaxTrkCh: 3, Flags: 0x010000}, // SBAS disabled
{GnssId: 3, ResTrkCh: 8, MaxTrkCh: 16, Flags: 0x010000}, // BeiDou disabled
{GnssId: 5, ResTrkCh: 0, MaxTrkCh: 3, Flags: 0x010000}, // QZSS disabled
{GnssId: 6, ResTrkCh: 8, MaxTrkCh: 14, Flags: 0x010000}, // GLONASS disabled
},
}
// SetGNSSDisable sends UBX-CFG-GNSS command to disable all GNSS but GPS
func (d *Device) SetGNSSDisable() (err error) {
err = gnssDisableCmd.Put(d.buffer[:])
if err != nil {
return err
}
return d.SendCommand(d.buffer[:])
}
// SendCommand sends a UBX command and waits for ACK/NAK response
func (d *Device) SendCommand(command []byte) error {
// Calculate and append checksum
checksummed := appendChecksum(command)
d.WriteBytes(checksummed)
func sendCommand(d Device, command []byte) (err error) {
d.WriteBytes(command)
start := time.Now()
for time.Since(start) < time.Second {
// Look for UBX sync sequence
if d.readNextByte() != ubxSyncChar1 {
continue
}
if d.readNextByte() != ubxSyncChar2 {
continue
}
// Read message class and ID
msgClass := d.readNextByte()
msgID := d.readNextByte()
// Check if it's an ACK class message
if msgClass != ubxClassACK {
continue
}
// Read length (2 bytes, little-endian) - ACK is always 2 bytes payload
lenLo := d.readNextByte()
lenHi := d.readNextByte()
length := uint16(lenLo) | uint16(lenHi)<<8
if length != 2 {
continue
}
// Read ACK payload: class and ID of acknowledged message
ackClass := d.readNextByte()
ackID := d.readNextByte()
// Verify ACK is for our command (command[2] = class, command[3] = ID)
if ackClass != command[2] || ackID != command[3] {
continue
}
if msgID == ubxACK_ACK {
return nil
}
if msgID == ubxACK_NAK {
return errGPSCommandRejected
for time.Now().Sub(start) < 1000 {
if d.readNextByte() == '\n' {
if d.readNextByte() == 0xB5 {
d.readNextByte()
if d.readNextByte() == 0x05 {
if d.readNextByte() == 0x01 {
return
}
}
}
}
}
return errNoACKToGPSCommand
}
// appendChecksum calculates UBX checksum and appends it to the message
func appendChecksum(msg []byte) []byte {
var ckA, ckB byte
// Checksum covers class, ID, length, and payload (skip sync chars)
for i := 2; i < len(msg); i++ {
ckA += msg[i]
ckB += ckA
}
return append(msg, ckA, ckB)
return errors.New("no ACK to GPS command")
}
-353
View File
@@ -1,353 +0,0 @@
package gps
import (
"testing"
)
func TestAppendChecksum(t *testing.T) {
testCases := []struct {
name string
input []byte
expected []byte
}{
{
name: "simple message",
input: []byte{0xB5, 0x62, 0x06, 0x24, 0x00, 0x00},
expected: []byte{0xB5, 0x62, 0x06, 0x24, 0x00, 0x00, 0x2A, 0x84},
},
{
name: "CFG-NAV5 header only",
input: []byte{0xB5, 0x62, 0x06, 0x24, 0x24, 0x00},
expected: []byte{0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0x4E, 0xCC},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := appendChecksum(tc.input)
if len(result) != len(tc.expected) {
t.Errorf("expected length %d, got %d", len(tc.expected), len(result))
return
}
// Check checksum bytes (last two bytes)
ckA := result[len(result)-2]
ckB := result[len(result)-1]
expectedCkA := tc.expected[len(tc.expected)-2]
expectedCkB := tc.expected[len(tc.expected)-1]
if ckA != expectedCkA || ckB != expectedCkB {
t.Errorf("expected checksum 0x%02X 0x%02X, got 0x%02X 0x%02X",
expectedCkA, expectedCkB, ckA, ckB)
}
})
}
}
func TestAppendChecksumPreservesOriginal(t *testing.T) {
input := []byte{0xB5, 0x62, 0x06, 0x24, 0x00, 0x00}
original := make([]byte, len(input))
copy(original, input)
result := appendChecksum(input)
// Verify original bytes are preserved
for i := range input {
if result[i] != original[i] {
t.Errorf("byte %d changed: expected 0x%02X, got 0x%02X", i, original[i], result[i])
}
}
// Verify two bytes were appended
if len(result) != len(input)+2 {
t.Errorf("expected length %d, got %d", len(input)+2, len(result))
}
}
func TestNav5CmdConfig(t *testing.T) {
// Verify nav5Cmd has expected values
if nav5Cmd.DynModel != 6 {
t.Errorf("expected DynModel 6 (airborne <1g), got %d", nav5Cmd.DynModel)
}
if nav5Cmd.FixMode != 3 {
t.Errorf("expected FixMode 3 (auto 2D/3D), got %d", nav5Cmd.FixMode)
}
expectedMask := CfgNav5Dyn | CfgNav5MinEl | CfgNav5PosFixMode
if nav5Cmd.Mask != expectedMask {
t.Errorf("expected Mask 0x%04X, got 0x%04X", expectedMask, nav5Cmd.Mask)
}
if nav5Cmd.MinElev_deg != 5 {
t.Errorf("expected MinElev_deg 5, got %d", nav5Cmd.MinElev_deg)
}
}
func TestGNSSDisableCmdConfig(t *testing.T) {
// Verify GNSSDisableCmd has expected structure
if gnssDisableCmd.MsgVer != 0 {
t.Errorf("expected MsgVer 0, got %d", gnssDisableCmd.MsgVer)
}
if gnssDisableCmd.NumTrkChHw != 0x20 {
t.Errorf("expected NumTrkChHw 0x20, got 0x%02X", gnssDisableCmd.NumTrkChHw)
}
if len(gnssDisableCmd.ConfigBlocks) != 5 {
t.Errorf("expected 5 config blocks, got %d", len(gnssDisableCmd.ConfigBlocks))
return
}
// Verify GPS is enabled
gpsBlock := gnssDisableCmd.ConfigBlocks[0]
if gpsBlock.GnssId != 0 {
t.Errorf("expected first block GnssId 0 (GPS), got %d", gpsBlock.GnssId)
}
if gpsBlock.Flags&CfgGnssEnable == 0 {
t.Error("expected GPS to be enabled")
}
// Verify other GNSS are disabled
for i := 1; i < len(gnssDisableCmd.ConfigBlocks); i++ {
block := gnssDisableCmd.ConfigBlocks[i]
if block.Flags&CfgGnssEnable != 0 {
t.Errorf("expected block %d (GnssId %d) to be disabled", i, block.GnssId)
}
}
}
func TestNav5CmdWrite(t *testing.T) {
buf := make([]byte, 64)
nav5Cmd.Put42Bytes(buf)
// Verify sync chars
if buf[0] != 0xB5 || buf[1] != 0x62 {
t.Errorf("expected sync 0xB5 0x62, got 0x%02X 0x%02X", buf[0], buf[1])
}
// Verify class/id
if buf[2] != 0x06 || buf[3] != 0x24 {
t.Errorf("expected class/id 0x06 0x24, got 0x%02X 0x%02X", buf[2], buf[3])
}
// Verify DynModel at offset 8
if buf[8] != 6 {
t.Errorf("expected DynModel 6, got %d", buf[8])
}
}
func TestGNSSDisableCmdWrite(t *testing.T) {
buf := make([]byte, 64)
err := gnssDisableCmd.Put(buf)
if err != nil {
t.Errorf("unexpected error, likely buffer too short for data: %v", err)
}
// 6 header + 4 payload header + 5*8 blocks = 50 bytes
const expectedLen = 6 + 4 + 5*8
sz := gnssDisableCmd.Size()
if sz != expectedLen {
t.Errorf("expected %d bytes, got %d", expectedLen, sz)
}
// Verify sync chars
if buf[0] != 0xB5 || buf[1] != 0x62 {
t.Errorf("expected sync 0xB5 0x62, got 0x%02X 0x%02X", buf[0], buf[1])
}
// Verify class/id
if buf[2] != 0x06 || buf[3] != 0x3E {
t.Errorf("expected class/id 0x06 0x3E, got 0x%02X 0x%02X", buf[2], buf[3])
}
// Verify number of blocks
if buf[9] != 5 {
t.Errorf("expected 5 blocks, got %d", buf[9])
}
}
func TestChecksumCalculation(t *testing.T) {
// Test with known UBX message and expected checksum
// This is a minimal CFG-NAV5 poll message
msg := []byte{0xB5, 0x62, 0x06, 0x24, 0x00, 0x00}
result := appendChecksum(msg)
// Verify checksum by recalculating
var ckA, ckB byte
for i := 2; i < len(msg); i++ {
ckA += msg[i]
ckB += ckA
}
if result[6] != ckA || result[7] != ckB {
t.Errorf("checksum mismatch: expected 0x%02X 0x%02X, got 0x%02X 0x%02X",
ckA, ckB, result[6], result[7])
}
}
func TestMessageRateCmdConfigs(t *testing.T) {
testCases := []struct {
name string
cmd CfgMsg1
msgClass byte
msgID byte
rate byte
}{
{"GGA", messageRateGGACmd, 0xF0, 0x00, 1},
{"GLL", messageRateGLLCmd, 0xF0, 0x01, 1},
{"GSA", messageRateGSACmd, 0xF0, 0x02, 0},
{"GSV", messageRateGSVCmd, 0xF0, 0x03, 0},
{"RMC", messageRateRMCCmd, 0xF0, 0x04, 1},
{"VTG", messageRateVTGCmd, 0xF0, 0x05, 0},
{"ZDA", messageRateZDACmd, 0xF0, 0x08, 0},
{"TXT", messageRateTXTCmd, 0xF0, 0x41, 0},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.cmd.MsgClass != tc.msgClass {
t.Errorf("expected MsgClass 0x%02X, got 0x%02X", tc.msgClass, tc.cmd.MsgClass)
}
if tc.cmd.MsgID != tc.msgID {
t.Errorf("expected MsgID 0x%02X, got 0x%02X", tc.msgID, tc.cmd.MsgID)
}
if tc.cmd.Rate != tc.rate {
t.Errorf("expected Rate %d, got %d", tc.rate, tc.cmd.Rate)
}
})
}
}
func TestCfgMsg1Write(t *testing.T) {
cmd := CfgMsg1{
MsgClass: 0xF0,
MsgID: 0x00,
Rate: 1,
}
buf := make([]byte, 16)
cmd.Put9Bytes(buf)
// Verify sync chars
if buf[0] != 0xB5 || buf[1] != 0x62 {
t.Errorf("expected sync 0xB5 0x62, got 0x%02X 0x%02X", buf[0], buf[1])
}
// Verify class/id (0x06 0x01 for CFG-MSG)
if buf[2] != 0x06 || buf[3] != 0x01 {
t.Errorf("expected class/id 0x06 0x01, got 0x%02X 0x%02X", buf[2], buf[3])
}
// Verify length (3 bytes payload)
if buf[4] != 3 || buf[5] != 0 {
t.Errorf("expected length 3, got %d", uint16(buf[4])|uint16(buf[5])<<8)
}
// Verify payload
if buf[6] != 0xF0 {
t.Errorf("expected MsgClass 0xF0, got 0x%02X", buf[6])
}
if buf[7] != 0x00 {
t.Errorf("expected MsgID 0x00, got 0x%02X", buf[7])
}
if buf[8] != 1 {
t.Errorf("expected Rate 1, got %d", buf[8])
}
}
func TestCfgMsg1ClassID(t *testing.T) {
cmd := CfgMsg1{}
if got := cmd.classID(); got != 0x0106 {
t.Errorf("expected 0x0106, got 0x%04x", got)
}
}
func TestMinimalMessageRatesConfig(t *testing.T) {
// Verify the minimal config has correct rates set
// GGA and RMC should be enabled (rate=1), others disabled (rate=0)
expectedRates := map[byte]byte{
0x00: 1, // GGA - enabled
0x01: 1, // GLL - enabled
0x02: 0, // GSA - disabled
0x03: 0, // GSV - disabled
0x04: 1, // RMC - enabled
0x05: 0, // VTG - disabled
0x08: 0, // ZDA - disabled
0x41: 0, // TXT - disabled
}
commands := []CfgMsg1{
messageRateGGACmd,
messageRateGLLCmd,
messageRateGSACmd,
messageRateGSVCmd,
messageRateRMCCmd,
messageRateVTGCmd,
messageRateZDACmd,
messageRateTXTCmd,
}
for _, cmd := range commands {
expectedRate, ok := expectedRates[cmd.MsgID]
if !ok {
t.Errorf("unexpected MsgID 0x%02X", cmd.MsgID)
continue
}
if cmd.Rate != expectedRate {
t.Errorf("MsgID 0x%02X: expected rate %d, got %d", cmd.MsgID, expectedRate, cmd.Rate)
}
}
}
func TestAllMessageRatesWriteCorrectBytes(t *testing.T) {
// Test that each message rate command writes the correct bytes
commands := []CfgMsg1{
messageRateGGACmd,
messageRateGLLCmd,
messageRateGSACmd,
messageRateGSVCmd,
messageRateRMCCmd,
messageRateVTGCmd,
messageRateZDACmd,
messageRateTXTCmd,
}
for _, cmd := range commands {
buf := make([]byte, 16)
cmd.Put9Bytes(buf)
// Verify MsgClass in payload
if buf[6] != 0xF0 {
t.Errorf("MsgID 0x%02X: expected MsgClass 0xF0, got 0x%02X", cmd.MsgID, buf[6])
}
// Verify MsgID in payload
if buf[7] != cmd.MsgID {
t.Errorf("expected MsgID 0x%02X in payload, got 0x%02X", cmd.MsgID, buf[7])
}
// Verify Rate in payload
if buf[8] != cmd.Rate {
t.Errorf("MsgID 0x%02X: expected Rate %d, got %d", cmd.MsgID, cmd.Rate, buf[8])
}
}
}
func TestSetMessageRatesAllEnabledModifiesRate(t *testing.T) {
// Verify that when we copy a command and set Rate=1, it works correctly
cmd := messageRateGSACmd // This one is disabled by default
if cmd.Rate != 0 {
t.Errorf("expected GSA default rate 0, got %d", cmd.Rate)
}
// Simulate what SetMessageRatesAllEnabled does
cmd.Rate = 1
buf := make([]byte, 16)
cmd.Put9Bytes(buf)
if buf[8] != 1 {
t.Errorf("expected Rate 1 in buffer, got %d", buf[8])
}
}
-220
View File
@@ -1,220 +0,0 @@
package gps
import "io"
// UBX message classes
const (
ubxClassACK = 0x05
)
// UBX ACK message IDs
const (
ubxACK_NAK = 0x00 // Message not acknowledged
ubxACK_ACK = 0x01 // Message acknowledged
)
// UBX sync characters
const (
ubxSyncChar1 = 0xB5
ubxSyncChar2 = 0x62
)
const (
DynModePortable = 0
DynModeStationary = 2
DynModePedestrian = 3
DynModeAutomotive = 4
DynModeSea = 5
DynModeAirborne1g = 6
DynModeAirborne2g = 7
DynModeAirborne4g = 8
DynModeWristWatch = 9
DynModeBike = 10
)
const (
FixMode2D = 1
FixMode3D = 2
FixModeAuto = 3
)
// from https://github.com/daedaleanai/ublox/blob/main/ubx/messages.go
// Message ubx-cfg-nav5
// CfgNav5 (Get/set) Navigation engine settings
// Class/Id 0x06 0x24 (36 bytes)
// See the Navigation Configuration Settings Description for a detailed description of how these settings affect receiver operation.
type CfgNav5 struct {
Mask CfgNav5Mask // Parameters bitmask. Only the masked parameters will be applied.
DynModel byte // Dynamic platform model: 0: portable 2: stationary 3: pedestrian 4: automotive 5: sea 6: airborne with <1g acceleration 7: airborne with <2g acceleration 8: airborne with <4g acceleration 9: wrist-worn watch (not supported in protocol versions less than 18) 10: bike (supported in protocol versions 19. 2)
FixMode byte // Position fixing mode: 1: 2D only 2: 3D only 3: auto 2D/3D
FixedAlt_me2 int32 // [1e-2 m] Fixed altitude (mean sea level) for 2D fix mode
FixedAltVar_m2e4 uint32 // [1e-4 m^2] Fixed altitude variance for 2D mode
MinElev_deg int8 // [deg] Minimum elevation for a GNSS satellite to be used in NAV
DrLimit_s byte // [s] Reserved
PDop uint16 // Position DOP mask to use
TDop uint16 // Time DOP mask to use
PAcc_m uint16 // [m] Position accuracy mask
TAcc_m uint16 // [m] Time accuracy mask
StaticHoldThresh_cm_s byte // [cm/s] Static hold threshold
DgnssTimeout_s byte // [s] DGNSS timeout
CnoThreshNumSVs byte // Number of satellites required to have C/N0 above cnoThresh for a fix to be attempted
CnoThresh_dbhz byte // [dBHz] C/N0 threshold for deciding whether to attempt a fix
Reserved1 [2]byte // Reserved
StaticHoldMaxDist_m uint16 // [m] Static hold distance threshold (before quitting static hold)
UtcStandard byte // UTC standard to be used: 0: Automatic; receiver selects based on GNSS configuration (see GNSS time bases) 3: UTC as operated by the U.S. Naval Observatory (USNO); derived from GPS time 5: UTC as combined from multiple European laboratories; derived from Galileo time 6: UTC as operated by the former Soviet Union (SU); derived from GLONASS time 7: UTC as operated by the National Time Service Center (NTSC), China; derived from BeiDou time (not supported in protocol versions less than 16).
Reserved2 [5]byte // Reserved
}
func (CfgNav5) classID() uint16 { return 0x2406 }
type CfgNav5Mask uint16
var _ io.WriterTo = CfgNav5{} // compile time guarantee of interface implementation.
const (
CfgNav5Dyn CfgNav5Mask = 0x1 // Apply dynamic model settings
CfgNav5MinEl CfgNav5Mask = 0x2 // Apply minimum elevation settings
CfgNav5PosFixMode CfgNav5Mask = 0x4 // Apply fix mode settings
CfgNav5DrLim CfgNav5Mask = 0x8 // Reserved
CfgNav5PosMask CfgNav5Mask = 0x10 // Apply position mask settings
CfgNav5TimeMask CfgNav5Mask = 0x20 // Apply time mask settings
CfgNav5StaticHoldMask CfgNav5Mask = 0x40 // Apply static hold settings
CfgNav5DgpsMask CfgNav5Mask = 0x80 // Apply DGPS settings
CfgNav5CnoThreshold CfgNav5Mask = 0x100 // Apply CNO threshold settings (cnoThresh, cnoThreshNumSVs)
CfgNav5Utc CfgNav5Mask = 0x400 // Apply UTC settings (not supported in protocol versions less than 16).
)
func (cfg CfgNav5) Append(dst []byte) []byte {
var buf [42]byte
cfg.Put42Bytes(buf[:])
dst = append(dst, buf[:]...)
return dst
}
func (cfg CfgNav5) WriteTo(w io.Writer) (int64, error) {
var buf [42]byte
cfg.Put42Bytes(buf[:])
n, err := w.Write(buf[:])
return int64(n), err
}
// Write CfgNav5 message to buffer
func (cfg CfgNav5) Put42Bytes(buf []byte) {
_ = buf[41]
copy(buf, []byte{0xb5, 0x62, byte(cfg.classID()), byte(cfg.classID() >> 8), 36, 0})
buf[6] = byte(cfg.Mask)
buf[7] = byte(cfg.Mask >> 8)
buf[8] = cfg.DynModel
buf[9] = cfg.FixMode
buf[10] = byte(cfg.FixedAlt_me2)
buf[11] = byte(cfg.FixedAlt_me2 >> 8)
buf[12] = byte(cfg.FixedAlt_me2 >> 16)
buf[13] = byte(cfg.FixedAlt_me2 >> 24)
buf[14] = byte(cfg.FixedAltVar_m2e4)
buf[15] = byte(cfg.FixedAltVar_m2e4 >> 8)
buf[16] = byte(cfg.FixedAltVar_m2e4 >> 16)
buf[17] = byte(cfg.FixedAltVar_m2e4 >> 24)
buf[18] = byte(cfg.MinElev_deg)
buf[19] = cfg.DrLimit_s
buf[20] = byte(cfg.PDop)
buf[21] = byte(cfg.PDop >> 8)
buf[22] = byte(cfg.TDop)
buf[23] = byte(cfg.TDop >> 8)
buf[24] = byte(cfg.PAcc_m)
buf[25] = byte(cfg.PAcc_m >> 8)
buf[26] = byte(cfg.TAcc_m)
buf[27] = byte(cfg.TAcc_m >> 8)
buf[28] = cfg.StaticHoldThresh_cm_s
buf[29] = cfg.DgnssTimeout_s
buf[30] = cfg.CnoThreshNumSVs
buf[31] = cfg.CnoThresh_dbhz
copy(buf[32:34], cfg.Reserved1[:])
buf[34] = byte(cfg.StaticHoldMaxDist_m)
buf[35] = byte(cfg.StaticHoldMaxDist_m >> 8)
buf[36] = cfg.UtcStandard
copy(buf[37:42], cfg.Reserved2[:])
}
// Message ubx-cfg-msg
// CfgMsg1 (Get/set) Set message rate
// Class/Id 0x06 0x01 (3 bytes)
// Set message rate configuration for the current port. See also section How to change between protocols.
type CfgMsg1 struct {
MsgClass byte // Message class
MsgID byte // Message identifier
Rate byte // Send rate on current port
}
func (CfgMsg1) classID() uint16 { return 0x0106 }
func (cfg CfgMsg1) Put9Bytes(buf []byte) {
copy(buf, []byte{0xb5, 0x62, byte(cfg.classID()), byte(cfg.classID() >> 8), 3, 0})
buf[6] = cfg.MsgClass
buf[7] = cfg.MsgID
buf[8] = cfg.Rate
}
// Message ubx-cfg-gnss
// CfgGnss (Get/set) GNSS system configuration
// Class/Id 0x06 0x3e (4 + N*8 bytes)
// Gets or sets the GNSS system channel sharing configuration. If the receiver is sent a valid new configuration, it will respond with a UBX-ACK- ACK message and immediately change to the new configuration. Otherwise the receiver will reject the request, by issuing a UBX-ACK-NAK and continuing operation with the previous configuration. Configuration requirements: It is necessary for at least one major GNSS to be enabled, after applying the new configuration to the current one. It is also required that at least 4 tracking channels are available to each enabled major GNSS, i.e. maxTrkCh must have a minimum value of 4 for each enabled major GNSS. The number of tracking channels in use must not exceed the number of tracking channels available in hardware, and the sum of all reserved tracking channels needs to be less than or equal to the number of tracking channels in use. Notes: To avoid cross-correlation issues, it is recommended that GPS and QZSS are always both enabled or both disabled. Polling this message returns the configuration of all supported GNSS, whether enabled or not; it may also include GNSS unsupported by the particular product, but in such cases the enable flag will always be unset. See section GNSS Configuration for a discussion of the use of this message. See section Satellite Numbering for a description of the GNSS IDs available. Configuration specific to the GNSS system can be done via other messages (e. g. UBX-CFG-SBAS).
type CfgGnss struct {
MsgVer byte // Message version (0x00 for this version)
NumTrkChHw byte // Number of tracking channels available in hardware (read only)
NumTrkChUse byte // (Read only in protocol versions greater than 23) Number of tracking channels to use. Must be > 0, <= numTrkChHw. If 0xFF, then number of tracking channels to use will be set to numTrkChHw.
NumConfigBlocks byte `len:"ConfigBlocks"` // Number of configuration blocks following
ConfigBlocks []CfgGnssConfigBlocksType // len: NumConfigBlocks
}
func (CfgGnss) classID() uint16 { return 0x3e06 }
type CfgGnssConfigBlocksType struct {
GnssId byte // System identifier (see Satellite Numbering )
ResTrkCh byte // (Read only in protocol versions greater than 23) Number of reserved (minimum) tracking channels for this system.
MaxTrkCh byte // (Read only in protocol versions greater than 23) Maximum number of tracking channels used for this system. Must be > 0, >= resTrkChn, <= numTrkChUse and <= maximum number of tracking channels supported for this system.
Reserved1 byte // Reserved
Flags CfgGnssFlags // Bitfield of flags. At least one signal must be configured in every enabled system.
}
type CfgGnssFlags uint32
const (
CfgGnssEnable CfgGnssFlags = 0x1 // Enable this system
CfgGnssSigCfgMask CfgGnssFlags = 0xff0000 // Signal configuration mask When gnssId is 0 (GPS) 0x01 = GPS L1C/A 0x10 = GPS L2C 0x20 = GPS L5 When gnssId is 1 (SBAS) 0x01 = SBAS L1C/A When gnssId is 2 (Galileo) 0x01 = Galileo E1 (not supported in protocol versions less than 18) 0x10 = Galileo E5a 0x20 = Galileo E5b When gnssId is 3 (BeiDou) 0x01 = BeiDou B1I 0x10 = BeiDou B2I 0x80 = BeiDou B2A When gnssId is 4 (IMES) 0x01 = IMES L1 When gnssId is 5 (QZSS) 0x01 = QZSS L1C/A 0x04 = QZSS L1S 0x10 = QZSS L2C 0x20 = QZSS L5 When gnssId is 6 (GLONASS) 0x01 = GLONASS L1 0x10 = GLONASS L2
)
// Write CfgGnss message to buffer
func (cfg CfgGnss) Put(buf []byte) error {
sz := cfg.Size()
if sz > len(buf) {
return io.ErrShortBuffer
}
copy(buf, []byte{0xb5, 0x62, byte(cfg.classID()), byte(cfg.classID() >> 8), 4 + byte(len(cfg.ConfigBlocks))*8, 0})
buf[6] = cfg.MsgVer
buf[7] = cfg.NumTrkChHw
buf[8] = cfg.NumTrkChUse
buf[9] = byte(len(cfg.ConfigBlocks))
offset := 10
for _, block := range cfg.ConfigBlocks {
buf[offset] = block.GnssId
buf[offset+1] = block.ResTrkCh
buf[offset+2] = block.MaxTrkCh
buf[offset+3] = block.Reserved1
buf[offset+4] = byte(block.Flags)
buf[offset+5] = byte(block.Flags >> 8)
buf[offset+6] = byte(block.Flags >> 16)
buf[offset+7] = byte(block.Flags >> 24)
offset += 8
}
return nil
}
// Size returns length of CfgGnss in bytes when sent over the wire.
func (cfg CfgGnss) Size() int {
return 10 + 8*len(cfg.ConfigBlocks)
}
-189
View File
@@ -1,189 +0,0 @@
package gps
import (
"testing"
)
func TestCfgNav5ClassID(t *testing.T) {
cfg := CfgNav5{}
if got := cfg.classID(); got != 0x2406 {
t.Errorf("expected 0x2406, got 0x%04x", got)
}
}
func TestCfgNav5Write(t *testing.T) {
cfg := CfgNav5{
Mask: CfgNav5Dyn | CfgNav5MinEl,
DynModel: 4,
FixMode: 3,
FixedAlt_me2: 10000,
FixedAltVar_m2e4: 10000,
MinElev_deg: 5,
DrLimit_s: 0,
PDop: 250,
TDop: 250,
PAcc_m: 100,
TAcc_m: 300,
StaticHoldThresh_cm_s: 50,
DgnssTimeout_s: 60,
CnoThreshNumSVs: 3,
CnoThresh_dbhz: 35,
Reserved1: [2]byte{0, 0},
StaticHoldMaxDist_m: 200,
UtcStandard: 0,
Reserved2: [5]byte{0, 0, 0, 0, 0},
}
buf := make([]byte, 64)
cfg.Put42Bytes(buf)
// Check sync chars
if buf[0] != 0xb5 || buf[1] != 0x62 {
t.Errorf("expected sync chars 0xb5 0x62, got 0x%02x 0x%02x", buf[0], buf[1])
}
// Check class/id (little-endian)
if buf[2] != 0x06 || buf[3] != 0x24 {
t.Errorf("expected class/id 0x06 0x24, got 0x%02x 0x%02x", buf[2], buf[3])
}
// Check length
if buf[4] != 36 || buf[5] != 0 {
t.Errorf("expected length 36, got %d", uint16(buf[4])|uint16(buf[5])<<8)
}
// Check Mask (little-endian)
mask := uint16(buf[6]) | uint16(buf[7])<<8
if mask != uint16(CfgNav5Dyn|CfgNav5MinEl) {
t.Errorf("expected mask 0x03, got 0x%04x", mask)
}
// Check DynModel
if buf[8] != 4 {
t.Errorf("expected DynModel 4, got %d", buf[8])
}
// Check FixMode
if buf[9] != 3 {
t.Errorf("expected FixMode 3, got %d", buf[9])
}
// Check FixedAlt_me2 (little-endian int32)
fixedAlt := int32(buf[10]) | int32(buf[11])<<8 | int32(buf[12])<<16 | int32(buf[13])<<24
if fixedAlt != 10000 {
t.Errorf("expected FixedAlt_me2 10000, got %d", fixedAlt)
}
}
func TestCfgGnssClassID(t *testing.T) {
cfg := CfgGnss{}
if got := cfg.classID(); got != 0x3e06 {
t.Errorf("expected 0x3e06, got 0x%04x", got)
}
}
func TestCfgGnssWrite(t *testing.T) {
testCases := []struct {
name string
cfg CfgGnss
expectedLen int
expectedBlocks byte
}{
{
name: "no config blocks",
cfg: CfgGnss{
MsgVer: 0,
NumTrkChHw: 32,
NumTrkChUse: 32,
ConfigBlocks: nil,
},
expectedLen: 10,
expectedBlocks: 0,
},
{
name: "one config block",
cfg: CfgGnss{
MsgVer: 0,
NumTrkChHw: 32,
NumTrkChUse: 32,
ConfigBlocks: []CfgGnssConfigBlocksType{
{GnssId: 0, ResTrkCh: 8, MaxTrkCh: 16, Flags: CfgGnssEnable | 0x010000},
},
},
expectedLen: 18,
expectedBlocks: 1,
},
{
name: "two config blocks",
cfg: CfgGnss{
MsgVer: 0,
NumTrkChHw: 32,
NumTrkChUse: 32,
ConfigBlocks: []CfgGnssConfigBlocksType{
{GnssId: 0, ResTrkCh: 8, MaxTrkCh: 16, Flags: CfgGnssEnable | 0x010000},
{GnssId: 6, ResTrkCh: 8, MaxTrkCh: 14, Flags: CfgGnssEnable | 0x010000},
},
},
expectedLen: 26,
expectedBlocks: 2,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
buf := make([]byte, 64)
err := tc.cfg.Put(buf)
if err != nil {
t.Errorf("unexpected error, data too long?: %v", err)
}
// Check sync chars
if buf[0] != 0xb5 || buf[1] != 0x62 {
t.Errorf("expected sync chars 0xb5 0x62, got 0x%02x 0x%02x", buf[0], buf[1])
}
// Check class/id (little-endian)
if buf[2] != 0x06 || buf[3] != 0x3e {
t.Errorf("expected class/id 0x06 0x3e, got 0x%02x 0x%02x", buf[2], buf[3])
}
// Check number of config blocks
if buf[9] != tc.expectedBlocks {
t.Errorf("expected %d config blocks, got %d", tc.expectedBlocks, buf[9])
}
})
}
}
func TestCfgGnssWriteBlockContent(t *testing.T) {
cfg := CfgGnss{
MsgVer: 0,
NumTrkChHw: 32,
NumTrkChUse: 32,
ConfigBlocks: []CfgGnssConfigBlocksType{
{GnssId: 0, ResTrkCh: 8, MaxTrkCh: 16, Reserved1: 0, Flags: CfgGnssEnable | 0x010000},
},
}
buf := make([]byte, 64)
err := cfg.Put(buf)
if err != nil {
t.Fatal(err)
}
// Check first block at offset 10
if buf[10] != 0 {
t.Errorf("expected GnssId 0, got %d", buf[10])
}
if buf[11] != 8 {
t.Errorf("expected ResTrkCh 8, got %d", buf[11])
}
if buf[12] != 16 {
t.Errorf("expected MaxTrkCh 16, got %d", buf[12])
}
// Check flags (little-endian uint32)
flags := uint32(buf[14]) | uint32(buf[15])<<8 | uint32(buf[16])<<16 | uint32(buf[17])<<24
expectedFlags := uint32(CfgGnssEnable | 0x010000)
if flags != expectedFlags {
t.Errorf("expected flags 0x%08x, got 0x%08x", expectedFlags, flags)
}
}
+10 -14
View File
@@ -60,20 +60,16 @@ const (
)
const (
Bandwidth_7_8 = iota // 7.8 kHz
Bandwidth_10_4 // 10.4 kHz
Bandwidth_15_6 // 15.6 kHz
Bandwidth_20_8 // 20.8 kHz
Bandwidth_31_25 // 31.25 kHz
Bandwidth_41_7 // 41.7 kHz
Bandwidth_62_5 // 62.5 kHz
Bandwidth_125_0 // 125.0 kHz
Bandwidth_203_125 // 203.125 kHz
Bandwidth_250_0 // 250.0 kHz
Bandwidth_406_25 // 406.25 kHz
Bandwidth_500_0 // 500.0 kHz
Bandwidth_812_5 // 812.5 kHz
Bandwidth_1625_0 // 1625 kHz
Bandwidth_7_8 = iota // 7.8 kHz
Bandwidth_10_4 // 10.4 kHz
Bandwidth_15_6 // 15.6 kHz
Bandwidth_20_8 // 20.8 kHz
Bandwidth_31_25 // 31.25 kHz
Bandwidth_41_7 // 41.7 kHz
Bandwidth_62_5 // 62.5 kHz
Bandwidth_125_0 // 125.0 kHz
Bandwidth_250_0 // 250.0 kHz
Bandwidth_500_0 // 500.0 kHz
)
const (
-3
View File
@@ -6,9 +6,6 @@ const (
RadioEventTimeout
RadioEventWatchdog
RadioEventCrcError
RadioEventValidHeader
RadioEventCadDone
RadioEventCadDetected
RadioEventUnhandled
)
+41 -45
View File
@@ -6,7 +6,6 @@
package mcp2515 // import "tinygo.org/x/drivers/mcp2515"
import (
"encoding/binary"
"errors"
"fmt"
"time"
@@ -16,30 +15,15 @@ import (
"tinygo.org/x/drivers/internal/pin"
)
var (
ErrNothingIsReceived = errors.New("readMsg: nothing is received")
ErrRequestNewModeMaxTimeEx = errors.New("requestNewMode max time expired")
ErrLengthIsLongerThanCapacity = errors.New("length is longer than capacity")
ErrTxTimeout = errors.New("Tx: Tx timeout")
ErrInvalidDirection = errors.New("invalid direction")
ErrInvalidParameter = errors.New("invalid parameter")
ErrCannotExpandBuffer = errors.New("cannot expand buffer (to avoid memory allocation)")
)
// Device wraps MCP2515 SPI CAN Module.
type Device struct {
spi SPI
cs pin.OutputFunc
msg *CANMsg
extended bool
mcpMode byte
configurePins func()
}
type Configuration struct {
Extended bool
}
// CANMsg stores CAN message fields.
type CANMsg struct {
ID uint32
@@ -72,11 +56,10 @@ func New(b drivers.SPI, csPin pin.Output) *Device {
}
// Configure sets up the device for communication.
func (d *Device) Configure(cfg Configuration) {
func (d *Device) Configure() {
if d.configurePins == nil {
panic(legacy.ErrConfigBeforeInstantiated)
}
d.extended = cfg.Extended
d.configurePins()
}
@@ -134,13 +117,9 @@ func (d *Device) Tx(canid uint32, dlc uint8, data []byte) error {
timeoutCount++
}
if timeoutCount == timeoutvalue {
return ErrTxTimeout
return fmt.Errorf("Tx: Tx timeout")
}
ext := byte(0)
if d.extended {
ext = 1
}
err = d.writeCANMsg(bufNum, canid, ext, 0, dlc, data)
err = d.writeCANMsg(bufNum, canid, 0, 0, dlc, data)
if err != nil {
return err
}
@@ -410,7 +389,7 @@ func (d *Device) configRate(speed, clock byte) error {
set = false
}
if !set {
return ErrInvalidParameter
return errors.New("invalid parameter")
}
if err := d.setRegister(mcpCNF1, cfg1); err != nil {
return err
@@ -470,7 +449,7 @@ func (d *Device) readMsg() error {
return err
}
} else {
return ErrNothingIsReceived
return fmt.Errorf("readMsg: nothing is received")
}
return nil
@@ -577,22 +556,39 @@ func (d *Device) writeCANMsg(bufNum uint8, canid uint32, ext, rtrBit, dlc uint8,
}
func (s *SPI) setTxBufData(canid uint32, ext, rtrBit, dlc uint8, data []byte) error {
var id [4]byte
canid = canid & 0x0FFFF
if ext == 1 {
canid = canid & extidBottom29Mask
extended_id := canid
high_11 := extended_id & extidTop11WriteMask
low_18 := extended_id & extidBottom18Mask
high_11 <<= 3
extended_id_shifted := high_11 | low_18
canid = extended_id_shifted | extidFlagMask
// TODO: add Extended ID
err := s.setTxData(0)
if err != nil {
return err
}
err = s.setTxData(0)
if err != nil {
return err
}
err = s.setTxData(0)
if err != nil {
return err
}
err = s.setTxData(0)
if err != nil {
return err
}
} else {
canid = canid & stdidBottom11Mask
canid <<= 16 + 5
}
binary.BigEndian.PutUint32(id[:], canid)
for _, b := range id {
err := s.setTxData(b)
err := s.setTxData(byte(canid >> 3))
if err != nil {
return err
}
err = s.setTxData(byte((canid & 0x07) << 5))
if err != nil {
return err
}
err = s.setTxData(0)
if err != nil {
return err
}
err = s.setTxData(0)
if err != nil {
return err
}
@@ -789,7 +785,7 @@ func (d *Device) requestNewMode(newMode byte) error {
if r&modeMask == newMode {
return nil
} else if e := time.Now(); e.Sub(s) > 200*time.Millisecond {
return ErrRequestNewModeMaxTimeEx
return errors.New("requestNewMode max time expired")
}
}
}
@@ -865,23 +861,23 @@ func (s *SPI) clearBuffer(dir int) error { return s.setBufferLength(0, dir) }
func (s *SPI) setBufferLength(length int, dir int) error {
if dir == tx {
if length > cap(s.tx) {
return ErrLengthIsLongerThanCapacity
return fmt.Errorf("length is longer than capacity")
}
s.tx = s.tx[:length]
} else if dir == rx {
if length > cap(s.rx) {
return ErrLengthIsLongerThanCapacity
return fmt.Errorf("length is longer than capacity")
}
s.rx = s.rx[:length]
} else {
return ErrInvalidDirection
return fmt.Errorf("invalid direction")
}
return nil
}
func (s *SPI) setTxData(data byte) error {
if len(s.tx) >= bufferSize {
return ErrCannotExpandBuffer
return fmt.Errorf("cannot expand buffer (to avoid memory allocation)")
}
s.tx = append(s.tx, data)
-7
View File
@@ -417,11 +417,4 @@ const (
canFail = 0xff
canMaxCharInMessage = 8
// for extended id
extidTop11WriteMask = 0x1FFC0000
extidBottom29Mask = (1 << 29) - 1 // extended id bits
extidBottom18Mask = (1 << 18) - 1 // bottom 18 bits
stdidBottom11Mask = 0x7FF
extidFlagMask = 1 << 19
)
+66 -145
View File
@@ -5,154 +5,75 @@ const AddressDefault = 0x60 // Assumes ADDR pin is low
const AddressAlternative = 0x61 // Assumes ADDR pin is high
const (
XTAL_FREQ = 25000000
PLL_FIXED = 80000000000
FREQ_MULT = 100
DEFAULT_CLK = 1000000000
OUTPUT_ENABLE_CONTROL = 3
PLL_VCO_MIN = 600000000
PLL_VCO_MAX = 900000000
MULTISYNTH_MIN_FREQ = 500000
MULTISYNTH_DIVBY4_FREQ = 150000000
MULTISYNTH_MAX_FREQ = 225000000
MULTISYNTH_SHARE_MAX = 100000000
MULTISYNTH_SHARE_MIN = 1024000
MULTISYNTH67_MAX_FREQ = MULTISYNTH_DIVBY4_FREQ
CLKOUT_MIN_FREQ = 4000
CLKOUT_MAX_FREQ = MULTISYNTH_MAX_FREQ
CLKOUT67_MS_MIN = PLL_VCO_MIN / MULTISYNTH67_A_MAX
CLKOUT67_MIN_FREQ = CLKOUT67_MS_MIN / 128
CLKOUT67_MAX_FREQ = MULTISYNTH67_MAX_FREQ
CLK0_CONTROL = 16
CLK1_CONTROL = 17
CLK2_CONTROL = 18
CLK3_CONTROL = 19
CLK4_CONTROL = 20
CLK5_CONTROL = 21
CLK6_CONTROL = 22
CLK7_CONTROL = 23
PLL_A_MIN = 15
PLL_A_MAX = 90
PLL_B_MAX = PLL_C_MAX - 1
PLL_C_MAX = 1048575
MULTISYNTH_A_MIN = 6
MULTISYNTH_A_MAX = 1800
MULTISYNTH67_A_MAX = 254
MULTISYNTH_B_MAX = MULTISYNTH_C_MAX - 1
MULTISYNTH_C_MAX = 1048575
MULTISYNTH_P1_MAX = (1 << 18) - 1
MULTISYNTH_P2_MAX = (1 << 20) - 1
MULTISYNTH_P3_MAX = (1 << 20) - 1
VCXO_PULL_MIN = 30
VCXO_PULL_MAX = 240
VCXO_MARGIN = 103
MULTISYNTH0_PARAMETERS_1 = 42
MULTISYNTH0_PARAMETERS_3 = 44
MULTISYNTH1_PARAMETERS_1 = 50
MULTISYNTH1_PARAMETERS_3 = 52
MULTISYNTH2_PARAMETERS_1 = 58
MULTISYNTH2_PARAMETERS_3 = 60
DEVICE_STATUS = 0
INTERRUPT_STATUS = 1
INTERRUPT_MASK = 2
STATUS_SYS_INIT = 1 << 7
STATUS_LOL_B = 1 << 6
STATUS_LOL_A = 1 << 5
STATUS_LOS = 1 << 4
OUTPUT_ENABLE_CTRL = 3
OEB_PIN_ENABLE_CTRL = 9
PLL_INPUT_SOURCE = 15
CLKIN_DIV_MASK = 3 << 6
CLKIN_DIV_1 = 0 << 6
CLKIN_DIV_2 = 1 << 6
CLKIN_DIV_4 = 2 << 6
CLKIN_DIV_8 = 3 << 6
PLLB_SOURCE = 1 << 3
PLLA_SOURCE = 1 << 2
SPREAD_SPECTRUM_PARAMETERS = 149
CLK0_CTRL = 16
CLK1_CTRL = 17
CLK2_CTRL = 18
CLK3_CTRL = 19
CLK4_CTRL = 20
CLK5_CTRL = 21
CLK6_CTRL = 22
CLK7_CTRL = 23
CLK_POWERDOWN = 1 << 7
CLK_INTEGER_MODE = 1 << 6
CLK_PLL_SELECT = 1 << 5
CLK_INVERT = 1 << 4
CLK_INPUT_MASK = 3 << 2
CLK_INPUT_XTAL = 0 << 2
CLK_INPUT_CLKIN = 1 << 2
CLK_INPUT_MULTISYNTH_0_4 = 2 << 2
CLK_INPUT_MULTISYNTH_N = 3 << 2
CLK_DRIVE_STRENGTH_MASK = 3 << 0
CLK_DRIVE_STRENGTH_2MA = 0 << 0
CLK_DRIVE_STRENGTH_4MA = 1 << 0
CLK_DRIVE_STRENGTH_6MA = 2 << 0
CLK_DRIVE_STRENGTH_8MA = 3 << 0
PLL_RESET = 177
CLK3_0_DISABLE_STATE = 24
CLK7_4_DISABLE_STATE = 25
CLK_DISABLE_STATE_MASK = 3
CLK_DISABLE_STATE_LOW = 0
CLK_DISABLE_STATE_HIGH = 1
CLK_DISABLE_STATE_FLOAT = 2
CLK_DISABLE_STATE_NEVER = 3
PARAMETERS_LENGTH = 8
PLLA_PARAMETERS = 26
PLLB_PARAMETERS = 34
CLK0_PARAMETERS = 42
CLK1_PARAMETERS = 50
CLK2_PARAMETERS = 58
CLK3_PARAMETERS = 66
CLK4_PARAMETERS = 74
CLK5_PARAMETERS = 82
CLK6_PARAMETERS = 90
CLK7_PARAMETERS = 91
CLK6_7_OUTPUT_DIVIDER = 92
OUTPUT_CLK_DIV_MASK = 7 << 4
OUTPUT_CLK6_DIV_MASK = 7 << 0
OUTPUT_CLK_DIV_SHIFT = 4
OUTPUT_CLK_DIV6_SHIFT = 0
OUTPUT_CLK_DIV_1 = 0
OUTPUT_CLK_DIV_2 = 1
OUTPUT_CLK_DIV_4 = 2
OUTPUT_CLK_DIV_8 = 3
OUTPUT_CLK_DIV_16 = 4
OUTPUT_CLK_DIV_32 = 5
OUTPUT_CLK_DIV_64 = 6
OUTPUT_CLK_DIV_128 = 7
OUTPUT_CLK_DIVBY4 = 3 << 2
SSC_PARAM0 = 149
SSC_PARAM1 = 150
SSC_PARAM2 = 151
SSC_PARAM3 = 152
SSC_PARAM4 = 153
SSC_PARAM5 = 154
SSC_PARAM6 = 155
SSC_PARAM7 = 156
SSC_PARAM8 = 157
SSC_PARAM9 = 158
SSC_PARAM10 = 159
SSC_PARAM11 = 160
SSC_PARAM12 = 161
VXCO_PARAMETERS_LOW = 162
VXCO_PARAMETERS_MID = 163
VXCO_PARAMETERS_HIGH = 164
CLK0_PHASE_OFFSET = 165
CLK1_PHASE_OFFSET = 166
CLK2_PHASE_OFFSET = 167
CLK3_PHASE_OFFSET = 168
CLK4_PHASE_OFFSET = 169
CLK5_PHASE_OFFSET = 170
PLL_RESET = 177
PLL_RESET_B = 1 << 7
PLL_RESET_A = 1 << 5
CRYSTAL_LOAD = 183
CRYSTAL_LOAD_MASK = 3 << 6
CRYSTAL_LOAD_0PF = 0 << 6
CRYSTAL_LOAD_6PF = 1 << 6
CRYSTAL_LOAD_8PF = 2 << 6
CRYSTAL_LOAD_10PF = 3 << 6
FANOUT_ENABLE = 187
CLKIN_ENABLE = 1 << 7
XTAL_ENABLE = 1 << 6
MULTISYNTH_ENABLE = 1 << 4
CRYSTAL_INTERNAL_LOAD_CAPACITANCE = 183
)
const (
CRYSTAL_LOAD_6PF = (1 << 6)
CRYSTAL_LOAD_8PF = (2 << 6)
CRYSTAL_LOAD_10PF = (3 << 6)
)
const (
CRYSTAL_FREQ_25MHZ = 25000000
CRYSTAL_FREQ_27MHZ = 27000000
)
const (
PLL_A = iota
PLL_B
)
const (
R_DIV_1 = iota
R_DIV_2
R_DIV_4
R_DIV_8
R_DIV_16
R_DIV_32
R_DIV_64
R_DIV_128
)
const (
MULTISYNTH_DIV_4 = 4
MULTISYNTH_DIV_6 = 6
MULTISYNTH_DIV_8 = 8
)
// Frequency constants (in Hz)
const (
CLKOUT_MIN_FREQ = 8000 // 8 kHz
CLKOUT_MAX_FREQ = 150000000 // 150 MHz
MULTISYNTH_MAX_FREQ = 150000000 // 150 MHz
MULTISYNTH_SHARE_MAX = 100000000 // 100 MHz
MULTISYNTH_DIVBY4_FREQ = 150000000 // 150 MHz
PLL_VCO_MIN = 600000000 // 600 MHz
PLL_VCO_MAX = 900000000 // 900 MHz
)
const (
SI5351_PLL_C_MAX = 1048575
)
+557 -997
View File
File diff suppressed because it is too large Load Diff
-214
View File
@@ -1,214 +0,0 @@
package si5351
import (
"testing"
)
func TestSelectRDiv(t *testing.T) {
d := &Device{}
tests := []struct {
name string
freq Frequency
wantDiv uint8
wantFreq Frequency
}{
{"4kHz", 4000 * FREQ_MULT, OUTPUT_CLK_DIV_128, 4000 * FREQ_MULT * 128},
{"8kHz", 8000 * FREQ_MULT, OUTPUT_CLK_DIV_64, 8000 * FREQ_MULT * 64},
{"16kHz", 16000 * FREQ_MULT, OUTPUT_CLK_DIV_32, 16000 * FREQ_MULT * 32},
{"32kHz", 32000 * FREQ_MULT, OUTPUT_CLK_DIV_16, 32000 * FREQ_MULT * 16},
{"64kHz", 64000 * FREQ_MULT, OUTPUT_CLK_DIV_8, 64000 * FREQ_MULT * 8},
{"128kHz", 128000 * FREQ_MULT, OUTPUT_CLK_DIV_4, 128000 * FREQ_MULT * 4},
{"256kHz", 256000 * FREQ_MULT, OUTPUT_CLK_DIV_2, 256000 * FREQ_MULT * 2},
{"512kHz", 512000 * FREQ_MULT, OUTPUT_CLK_DIV_1, 512000 * FREQ_MULT},
{"1MHz", 1000000 * FREQ_MULT, OUTPUT_CLK_DIV_1, 1000000 * FREQ_MULT},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
freq := tt.freq
freq, gotDiv := d.selectRDiv(freq)
if gotDiv != tt.wantDiv {
t.Errorf("selectRDiv() div = %v, want %v", gotDiv, tt.wantDiv)
}
if freq != tt.wantFreq {
t.Errorf("selectRDiv() freq = %v, want %v", freq, tt.wantFreq)
}
})
}
}
func TestSelectRDivMS67(t *testing.T) {
d := &Device{}
tests := []struct {
name string
freq Frequency
wantDiv uint8
wantFreq Frequency
}{
{"4kHz", 4000 * FREQ_MULT, OUTPUT_CLK_DIV_128, 4000 * FREQ_MULT * 128},
{"8kHz", 8000 * FREQ_MULT, OUTPUT_CLK_DIV_64, 8000 * FREQ_MULT * 64},
{"16kHz", 16000 * FREQ_MULT, OUTPUT_CLK_DIV_32, 16000 * FREQ_MULT * 32},
{"64kHz", 64000 * FREQ_MULT, OUTPUT_CLK_DIV_8, 64000 * FREQ_MULT * 8},
{"256kHz", 256000 * FREQ_MULT, OUTPUT_CLK_DIV_2, 256000 * FREQ_MULT * 2},
{"512kHz", 512000 * FREQ_MULT, OUTPUT_CLK_DIV_1, 512000 * FREQ_MULT},
{"1MHz", 1000000 * FREQ_MULT, OUTPUT_CLK_DIV_1, 1000000 * FREQ_MULT},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
freq := tt.freq
freq, gotDiv := d.selectRDivMS67(freq)
if gotDiv != tt.wantDiv {
t.Errorf("selectRDivMS67() div = %v, want %v", gotDiv, tt.wantDiv)
}
if freq != tt.wantFreq {
t.Errorf("selectRDivMS67() freq = %v, want %v", freq, tt.wantFreq)
}
})
}
}
func TestCalculatePLL(t *testing.T) {
d := &Device{}
d.crystalFreq[0] = 25000000
tests := []struct {
name string
freq Frequency
wantMin Frequency
wantMax Frequency
}{
{"600MHz", 600000000 * FREQ_MULT, 599000000 * FREQ_MULT, 601000000 * FREQ_MULT},
{"750MHz", 750000000 * FREQ_MULT, 749000000 * FREQ_MULT, 751000000 * FREQ_MULT},
{"900MHz", 900000000 * FREQ_MULT, 899000000 * FREQ_MULT, 901000000 * FREQ_MULT},
{"BelowMin", 500000000 * FREQ_MULT, 600000000 * FREQ_MULT, 600000000 * FREQ_MULT},
{"AboveMax", 1000000000 * FREQ_MULT, 900000000 * FREQ_MULT, 900000000 * FREQ_MULT},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, reg := d.CalculatePLL(PLL_A, tt.freq, 0, false)
if got < tt.wantMin || got > tt.wantMax {
t.Errorf("CalculatePLL() = %v, want between %v and %v", got, tt.wantMin, tt.wantMax)
}
if reg.p1 == 0 || reg.p3 == 0 {
t.Errorf("CalculatePLL() invalid register values: p1=%v, p2=%v, p3=%v", reg.p1, reg.p2, reg.p3)
}
})
}
}
func TestCalculateMultisynth(t *testing.T) {
d := &Device{}
tests := []struct {
name string
freq Frequency
pllFreq Frequency
wantDiv bool
}{
{"10MHz from 800MHz", 10000000 * FREQ_MULT, 800000000 * FREQ_MULT, false},
{"1MHz from 800MHz", 1000000 * FREQ_MULT, 800000000 * FREQ_MULT, false},
{"Auto PLL 10MHz", 10000000 * FREQ_MULT, 0, false},
{"150MHz DivBy4", 150000000 * FREQ_MULT, 600000000 * FREQ_MULT, true},
{"BelowMin", 100000 * FREQ_MULT, 800000000 * FREQ_MULT, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, reg := d.CalculateMultisynth(tt.freq, tt.pllFreq)
if tt.pllFreq == 0 {
// Auto mode should return a valid PLL frequency
if got < PLL_VCO_MIN*FREQ_MULT || got > PLL_VCO_MAX*FREQ_MULT {
t.Errorf("CalculateMultisynth() returned invalid PLL freq %v", got)
}
}
if reg.p3 == 0 {
t.Errorf("CalculateMultisynth() p3 should not be 0")
}
})
}
}
func TestMultisynth67Calc(t *testing.T) {
d := &Device{}
tests := []struct {
name string
freq Frequency
pllFreq Frequency
wantErr bool
}{
{"10MHz Auto", 10000000 * FREQ_MULT, 0, false},
{"100MHz Auto", 100000000 * FREQ_MULT, 0, false},
{"100MHz from 800MHz", 100000000 * FREQ_MULT, 800000000 * FREQ_MULT, false},
{"Invalid Division", 10000000 * FREQ_MULT, 777000000 * FREQ_MULT, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, reg := d.multisynth67Calc(tt.freq, tt.pllFreq)
if tt.pllFreq == 0 {
if got < PLL_VCO_MIN*FREQ_MULT || got > PLL_VCO_MAX*FREQ_MULT {
t.Errorf("multisynth67Calc() returned invalid PLL freq %v", got)
}
} else if tt.wantErr {
if got != 0 {
t.Errorf("multisynth67Calc() should return 0 for invalid division, got %v", got)
}
}
if reg.p1 == 0 && !tt.wantErr {
t.Errorf("multisynth67Calc() p1 should not be 0")
}
})
}
}
func TestSetCorrection(t *testing.T) {
// Skip this test as it requires a mock I2C bus
t.Skip("Requires mock I2C bus implementation")
}
func TestSetRefFreq(t *testing.T) {
d := &Device{}
tests := []struct {
name string
freq CrystalFrequency
wantFreq CrystalFrequency
wantDiv uint8
}{
{"25MHz", 25000000, 25000000, CLKIN_DIV_1},
{"50MHz", 50000000, 25000000, CLKIN_DIV_2},
{"100MHz", 100000000, 25000000, CLKIN_DIV_4},
{"30MHz", 30000000, 30000000, CLKIN_DIV_1},
{"60MHz", 60000000, 30000000, CLKIN_DIV_2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d.SetReferenceFrequency(PLLInputClockIn, tt.freq)
if d.crystalFreq[PLLInputClockIn] != tt.wantFreq {
t.Errorf("SetReferenceFrequency() freq = %v, want %v", d.crystalFreq[PLLInputClockIn], tt.wantFreq)
}
if d.clkinDiv != tt.wantDiv {
t.Errorf("SetReferenceFrequency() clkinDiv = %v, want %v", d.clkinDiv, tt.wantDiv)
}
})
}
}
func TestGetCorrection(t *testing.T) {
d := &Device{}
d.refCorrection[PLLInputXO] = 5000
d.refCorrection[PLLInputClockIn] = -3000
if got := d.GetCorrection(PLLInputXO); got != 5000 {
t.Errorf("GetCorrection(PLLInputXO) = %v, want 5000", got)
}
if got := d.GetCorrection(PLLInputClockIn); got != -3000 {
t.Errorf("GetCorrection(PLLInputClockIn) = %v, want -3000", got)
}
}
+1 -3
View File
@@ -74,7 +74,7 @@ tinygo build -size short -o ./build/test.hex -target=xiao-rp2040 ./examples/ssd1
tinygo build -size short -o ./build/test.hex -target=thumby ./examples/ssd1306/
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/ssd1331/main.go
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/st7735/main.go
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/st7789/main.go
tinygo build -size short -o ./build/test.hex -target=clue ./examples/st7789/main.go
tinygo build -size short -o ./build/test.hex -target=circuitplay-express ./examples/thermistor/main.go
tinygo build -size short -o ./build/test.hex -target=circuitplay-bluefruit ./examples/tone
tinygo build -size short -o ./build/test.hex -target=arduino-nano33 ./examples/tm1637/main.go
@@ -124,11 +124,9 @@ tinygo build -size short -o ./build/test.uf2 -target=pico ./examples/xpt2046/mai
tinygo build -size short -o ./build/test.elf -target=m5stack-core2 ./examples/ft6336/basic/
tinygo build -size short -o ./build/test.elf -target=m5stack-core2 ./examples/ft6336/touchpaint/
tinygo build -size short -o ./build/test.hex -target=nucleo-wl55jc ./examples/sx126x/lora_rxtx/
tinygo build -size short -o ./build/test.hex -target=pybadge ./examples/sx127x/lora_rxtx/
tinygo build -size short -o ./build/test.uf2 -target=pico ./examples/ssd1289/main.go
tinygo build -size short -o ./build/test.hex -target=pico ./examples/irremote/main.go
tinygo build -size short -o ./build/test.hex -target=badger2040 ./examples/uc8151/main.go
tinygo build -size short -o ./build/test.hex -target=badger2040 ./examples/waveshare-epd/epd2in9v2/main.go
tinygo build -size short -o ./build/test.uf2 -target=pico ./examples/scd4x/main.go
tinygo build -size short -o ./build/test.uf2 -target=circuitplay-express ./examples/makeybutton/main.go
tinygo build -size short -o ./build/test.hex -target=arduino-nano33 ./examples/ds18b20/main.go
+16 -19
View File
@@ -5,13 +5,12 @@ package st7735 // import "tinygo.org/x/drivers/st7735"
import (
"image/color"
"machine"
"time"
"errors"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/legacy"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/pixel"
)
@@ -40,10 +39,10 @@ type Device = DeviceOf[pixel.RGB565BE]
// formats.
type DeviceOf[T Color] struct {
bus drivers.SPI
dcPin pin.OutputFunc
resetPin pin.OutputFunc
csPin pin.OutputFunc
blPin pin.OutputFunc
dcPin machine.Pin
resetPin machine.Pin
csPin machine.Pin
blPin machine.Pin
width int16
height int16
columnOffset int16
@@ -66,25 +65,23 @@ type Config struct {
}
// New creates a new ST7735 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) Device {
func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) Device {
return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
}
// NewOf creates a new ST7735 connection with a particular pixel format. The SPI
// wire must already be configured.
func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) DeviceOf[T] {
// IMPORTANT: pin configuration should really be done outside of this driver,
// but for backwards compatibility with existing code, we do it here.
legacy.ConfigurePinOut(dcPin)
legacy.ConfigurePinOut(resetPin)
legacy.ConfigurePinOut(csPin)
legacy.ConfigurePinOut(blPin)
func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) DeviceOf[T] {
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
return DeviceOf[T]{
bus: bus,
dcPin: dcPin.Set,
resetPin: resetPin.Set,
csPin: csPin.Set,
blPin: blPin.Set,
dcPin: dcPin,
resetPin: resetPin,
csPin: csPin,
blPin: blPin,
}
}
@@ -426,7 +423,7 @@ func (d *DeviceOf[T]) Data(data uint8) {
// Tx sends data to the display
func (d *DeviceOf[T]) Tx(data []byte, isCommand bool) {
d.dcPin(!isCommand)
d.dcPin.Set(!isCommand)
d.bus.Tx(data, nil)
}
+8
View File
@@ -0,0 +1,8 @@
package st7789
// Bus is the interface that wraps the basic Tx and Transfer methods
// for communication buses like SPI or Parallel.
type Bus interface {
Tx(w, r []byte) error
Transfer(w byte) (byte, error)
}
+57 -50
View File
@@ -4,56 +4,63 @@ import "tinygo.org/x/drivers"
// Registers
const (
NOP = 0x00
SWRESET = 0x01
RDDID = 0x04
RDDST = 0x09
SLPIN = 0x10
SLPOUT = 0x11
PTLON = 0x12
NORON = 0x13
INVOFF = 0x20
INVON = 0x21
DISPOFF = 0x28
DISPON = 0x29
CASET = 0x2A
RASET = 0x2B
RAMWR = 0x2C
RAMRD = 0x2E
PTLAR = 0x30
COLMOD = 0x3A
MADCTL = 0x36
MADCTL_MY = 0x80
MADCTL_MX = 0x40
MADCTL_MV = 0x20
MADCTL_ML = 0x10
MADCTL_RGB = 0x00
MADCTL_BGR = 0x08
MADCTL_MH = 0x04
RDID1 = 0xDA
RDID2 = 0xDB
RDID3 = 0xDC
RDID4 = 0xDD
FRMCTR1 = 0xB1
RGBCTRL = 0xB1
FRMCTR2 = 0xB2
PORCTRL = 0xB2
FRMCTR3 = 0xB3
INVCTR = 0xB4
DISSET5 = 0xB6
PWCTR1 = 0xC0
PWCTR2 = 0xC1
PWCTR3 = 0xC2
PWCTR4 = 0xC3
PWCTR5 = 0xC4
VMCTR1 = 0xC5
FRCTRL2 = 0xC6
PWCTR6 = 0xFC
GMCTRP1 = 0xE0
GMCTRN1 = 0xE1
GSCAN = 0x45
VSCRDEF = 0x33
VSCRSADD = 0x37
NOP = 0x00
SWRESET = 0x01
RDDID = 0x04
RDDST = 0x09
SLPIN = 0x10
SLPOUT = 0x11
PTLON = 0x12
NORON = 0x13
INVOFF = 0x20
INVON = 0x21
DISPOFF = 0x28
DISPON = 0x29
CASET = 0x2A
RASET = 0x2B
RAMWR = 0x2C
RAMRD = 0x2E
PTLAR = 0x30
VSCRDEF = 0x33
TEOFF = 0x34
TEON = 0x35
VSCRSADD = 0x37
COLMOD = 0x3A
MADCTL = 0x36
GSCAN = 0x45
PWCTRL1 = 0xD0
RDID1 = 0xDA
RDID2 = 0xDB
RDID3 = 0xDC
RDID4 = 0xDD
RAMCTRL = 0xB0
FRMCTR1 = 0xB1
RGBCTRL = 0xB1
FRMCTR2 = 0xB2
PORCTRL = 0xB2
FRMCTR3 = 0xB3
INVCTR = 0xB4
DISSET5 = 0xB6
GCTRL = 0xB7
VCOMS = 0xBB
LCMCTRL = 0xC0
PWCTR2 = 0xC1
VDVVRHEN = 0xC2
VRHS = 0xC3
VDVS = 0xC4
VMCTR1 = 0xC5
FRCTRL2 = 0xC6
PVGAMCTRL = 0xE0
NVGAMCTRL = 0xE1
PWCTR6 = 0xFC
MADCTL_RGB = 0x00
MADCTL_ROWORDER = 0x80
MADCTL_COLORDER = 0x40
MADCTL_SWAPXY = 0x20
MADCTL_SCANORDER = 0x10
MADCTL_BGR = 0x08
MADCTL_MH = 0x04
ColorRGB444 ColorFormat = 0b011
ColorRGB565 ColorFormat = 0b101
+141 -88
View File
@@ -7,13 +7,14 @@ package st7789 // import "tinygo.org/x/drivers/st7789"
import (
"image/color"
"machine"
"math"
"time"
"errors"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/legacy"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/pixel"
)
@@ -45,11 +46,11 @@ type Device = DeviceOf[pixel.RGB565BE]
// DeviceOf is a generic version of Device. It supports multiple different pixel
// formats.
type DeviceOf[T Color] struct {
bus drivers.SPI
dcPin machine.Pin
resetPin machine.Pin
csPin machine.Pin
blPin machine.Pin
bus Bus
dcPin pin.OutputFunc
resetPin pin.OutputFunc
csPin pin.OutputFunc
blPin pin.OutputFunc
width int16
height int16
columnOffsetCfg int16
@@ -68,13 +69,15 @@ type DeviceOf[T Color] struct {
// Config is the configuration for the display
type Config struct {
Width int16
Height int16
Rotation drivers.Rotation
RowOffset int16
ColumnOffset int16
FrameRate FrameRate
VSyncLines int16
Width int16
Height int16
Rotation drivers.Rotation
RowOffset int16
ColumnOffset int16
FrameRate FrameRate
VSyncLines int16
IdleModePorch byte
PartialModePorch byte
// Gamma control. Look in the LCD panel datasheet or provided example code
// to find these values. If not set, the defaults will be used.
@@ -83,23 +86,27 @@ type Config struct {
}
// New creates a new ST7789 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) Device {
func New(bus Bus, resetPin, dcPin, csPin, blPin pin.Output) Device {
return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
}
// NewOf creates a new ST7789 connection with a particular pixel format. The SPI
// wire must already be configured.
func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) DeviceOf[T] {
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
func NewOf[T Color](bus Bus, resetPin, dcPin, csPin, blPin pin.Output) DeviceOf[T] {
// IMPORTANT: pin configuration should really be done outside of this
// driver, but for backwards compatibility with existing code, we do it
// here.
legacy.ConfigurePinOut(dcPin)
legacy.ConfigurePinOut(resetPin)
legacy.ConfigurePinOut(csPin)
legacy.ConfigurePinOut(blPin)
return DeviceOf[T]{
bus: bus,
dcPin: dcPin,
resetPin: resetPin,
csPin: csPin,
blPin: blPin,
dcPin: dcPin.Set,
resetPin: resetPin.Set,
csPin: csPin.Set,
blPin: blPin.Set,
}
}
@@ -129,7 +136,7 @@ func (d *DeviceOf[T]) Configure(cfg Config) {
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
d.vSyncLines = cfg.VSyncLines
} else {
d.vSyncLines = 16
d.vSyncLines = 0 // Default: no VSYNC pause
}
d.batchLength = int32(d.width)
@@ -139,21 +146,18 @@ func (d *DeviceOf[T]) Configure(cfg Config) {
d.batchLength += d.batchLength & 1
// Reset the device
d.resetPin.High()
time.Sleep(50 * time.Millisecond)
d.resetPin.Low()
time.Sleep(50 * time.Millisecond)
d.resetPin.High()
time.Sleep(50 * time.Millisecond)
d.Reset()
// Common initialization
d.startWrite()
d.sendCommand(SWRESET, nil) // Soft reset
d.endWrite()
time.Sleep(150 * time.Millisecond) //
d.startWrite()
d.sendCommand(SLPOUT, nil) // Exit sleep mode
time.Sleep(150 * time.Millisecond) //
d.startWrite()
// enable frame sync signal if used
d.sendCommand(TEON, nil)
// Memory initialization
var zeroColor T
@@ -164,54 +168,121 @@ func (d *DeviceOf[T]) Configure(cfg Config) {
// Use default RGB565 color format.
d.setColorFormat(ColorRGB565) // 16 bits per pixel
}
time.Sleep(10 * time.Millisecond)
d.setRotation(d.rotation) // Memory orientation
d.setWindow(0, 0, d.width, d.height) // Full draw window
d.fillScreen(color.RGBA{0, 0, 0, 255}) // Clear screen
// Framerate
d.sendCommand(FRCTRL2, []byte{byte(d.frameRate)}) // Frame rate for normal mode (default 60Hz)
// Frame vertical sync and "porch"
//
// Front and back porch controls vertical scanline sync time before and after
// a frame, where memory can be safely written without tearing.
//
fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
// TODO: is this correct? fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
fp := byte(0x0c)
// TODO: is this correct? bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
bp := byte(0x0c)
if cfg.IdleModePorch == 0 {
cfg.IdleModePorch = 0x22 // Default value
}
if cfg.PartialModePorch == 0 {
cfg.PartialModePorch = 0x22 // Default value
}
d.sendCommand(PORCTRL, []byte{
bp, // Back porch 5bit (0x7F max 0x08 default)
fp, // Front porch 5bit (0x7F max 0x08 default)
0x00, // Seprarate porch (TODO: what is this?)
0x22, // Idle mode porch (4bit-back 4bit-front 0x22 default)
0x22, // Partial mode porch (4bit-back 4bit-front 0x22 default)
bp, // Back porch 5bit (0x7F max 0x08 default)
fp, // Front porch 5bit (0x7F max 0x08 default)
0x00, // Separate porch (TODO: what is this?)
cfg.IdleModePorch, // Idle mode porch (4bit-back 4bit-front 0x22 default)
cfg.PartialModePorch, // Partial mode porch (4bit-back 4bit-front 0x22 default)
})
// Ready to display
d.sendCommand(INVON, nil) // Inversion ON
time.Sleep(10 * time.Millisecond) //
// LCM control, power on sequence
d.sendCommand(LCMCTRL, []byte{0x2C})
// VDV and VRH Command Enable - 0x01 power on sequence
d.sendCommand(VDVVRHEN, []byte{0x01})
// VRH Set - 0x12 5.3+( vcom+vcom offset+vdv)
d.sendCommand(VRHS, []byte{0x12})
// VDV Set - 0x20 0V
d.sendCommand(VDVS, []byte{0x20})
// PWCTRL1 Power control 1 - power on sequence
d.sendCommand(PWCTRL1, []byte{0xA4, 0xA1})
// Framerate
d.sendCommand(FRCTRL2, []byte{byte(d.frameRate)}) // Frame rate for normal mode (default 60Hz)
// As noted in https://github.com/pimoroni/pimoroni-pico/issues/1040
// this is required to avoid a weird light grey banding issue with low brightness green.
// The banding is not visible without tweaking gamma settings (GMCTRP1 & GMCTRN1) but
// it makes sense to fix it anyway.
d.sendCommand(RAMCTRL, []byte{0x00, 0xC0})
// Set gamma tables, if configured.
if len(cfg.PVGAMCTRL) == 14 {
d.sendCommand(GMCTRP1, cfg.PVGAMCTRL) // PVGAMCTRL: Positive Voltage Gamma Control
d.sendCommand(PVGAMCTRL, cfg.PVGAMCTRL) // PVGAMCTRL: Positive Voltage Gamma Control
}
if len(cfg.NVGAMCTRL) == 14 {
d.sendCommand(GMCTRN1, cfg.NVGAMCTRL) // NVGAMCTRL: Negative Voltage Gamma Control
d.sendCommand(NVGAMCTRL, cfg.NVGAMCTRL) // NVGAMCTRL: Negative Voltage Gamma Control
}
d.sendCommand(NORON, nil) // Normal mode ON
time.Sleep(10 * time.Millisecond) //
switch {
case d.width == 240 && d.height == 240:
// command(reg::GCTRL, 1, "\x14");
// Gate Control - power on sequence for 240x240
d.sendCommand(GCTRL, []byte{0x35})
d.sendCommand(DISPON, nil) // Screen ON
time.Sleep(10 * time.Millisecond) //
// command(reg::VCOMS, 1, "\x37");
// VCOM Setting
d.sendCommand(VCOMS, []byte{0x37})
// command(reg::GMCTRP1, 14, "\xD0\x04\x0D\x11\x13\x2B\x3F\x54\x4C\x18\x0D\x0B\x1F\x23");
d.sendCommand(PVGAMCTRL, []byte{0xD0, 0x04, 0x0D, 0x11, 0x13, 0x2B, 0x3F, 0x54, 0x4C, 0x18, 0x0D, 0x0B, 0x1F, 0x23})
// command(reg::GMCTRN1, 14, "\xD0\x04\x0C\x11\x13\x2C\x3F\x44\x51\x2F\x1F\x1F\x20\x23");
d.sendCommand(NVGAMCTRL, []byte{0xD0, 0x04, 0x0C, 0x11, 0x13, 0x2C, 0x3F, 0x44, 0x51, 0x2F, 0x1F, 0x1F, 0x20, 0x23})
case d.width == 320 && d.height == 240:
// Gate Control - power on sequence for 320x240
d.sendCommand(GCTRL, []byte{0x35})
// VCOM Setting - 0.875V
d.sendCommand(VCOMS, []byte{0x1f})
// command(reg::GMCTRP1, 14, "\xD0\x08\x11\x08\x0C\x15\x39\x33\x50\x36\x13\x14\x29\x2D");
d.sendCommand(PVGAMCTRL, []byte{0xD0, 0x08, 0x11, 0x08, 0x0C, 0x15, 0x39, 0x33, 0x50, 0x36, 0x13, 0x14, 0x29, 0x2D})
// command(reg::GMCTRN1, 14, "\xD0\x08\x10\x08\x06\x06\x39\x44\x51\x0B\x16\x14\x2F\x31");
d.sendCommand(NVGAMCTRL, []byte{0xD0, 0x08, 0x10, 0x08, 0x06, 0x06, 0x39, 0x44, 0x51, 0x0B, 0x16, 0x14, 0x2F, 0x31})
}
// Ready to display
d.sendCommand(INVON, nil) // Inversion ON
d.sendCommand(SLPOUT, nil) // Exit sleep mode
d.sendCommand(DISPON, nil) // Screen ON
d.endWrite()
time.Sleep(100 * time.Millisecond)
d.startWrite()
d.setRotation(d.rotation) // Memory orientation
d.setWindow(0, 0, d.width, d.height) // Full draw window
d.fillScreen(color.RGBA{0, 0, 0, 255}) // Clear screen
d.endWrite()
time.Sleep(50 * time.Millisecond)
d.blPin.High() // Backlight ON
}
// Reset performs a hardware reset of the display.
func (d *DeviceOf[T]) Reset() {
d.resetPin.High()
time.Sleep(50 * time.Millisecond)
d.resetPin.Low()
time.Sleep(50 * time.Millisecond)
d.resetPin.High()
time.Sleep(50 * time.Millisecond)
}
// Send a command with data to the display. It does not change the chip select
// pin (it must be low when calling). The DC pin is left high after return,
// meaning that data can be sent right away.
@@ -229,7 +300,7 @@ func (d *DeviceOf[T]) sendCommand(command uint8, data []byte) error {
// startWrite must be called at the beginning of all exported methods to set the
// chip select pin low.
func (d *DeviceOf[T]) startWrite() {
if d.csPin != machine.NoPin {
if d.csPin != nil {
d.csPin.Low()
}
}
@@ -237,7 +308,7 @@ func (d *DeviceOf[T]) startWrite() {
// endWrite must be called at the end of all exported methods to set the chip
// select pin high.
func (d *DeviceOf[T]) endWrite() {
if d.csPin != machine.NoPin {
if d.csPin != nil {
d.csPin.High()
}
}
@@ -509,18 +580,20 @@ func (d *DeviceOf[T]) setRotation(rotation Rotation) error {
madctl := uint8(0)
switch rotation % 4 {
case drivers.Rotation0:
madctl = MADCTL_COLORDER
madctl |= MADCTL_SWAPXY | MADCTL_SCANORDER
d.rowOffset = 0
d.columnOffset = 0
case drivers.Rotation90:
madctl = MADCTL_MX | MADCTL_MV
d.rowOffset = d.columnOffsetCfg
d.columnOffset = d.rowOffsetCfg
madctl = MADCTL_COLORDER | MADCTL_SWAPXY
d.rowOffset = 0
d.columnOffset = 0
case drivers.Rotation180:
madctl = MADCTL_MX | MADCTL_MY
madctl = MADCTL_COLORDER | MADCTL_ROWORDER
d.rowOffset = d.rowOffsetCfg
d.columnOffset = d.columnOffsetCfg
case drivers.Rotation270:
madctl = MADCTL_MY | MADCTL_MV
madctl = MADCTL_ROWORDER | MADCTL_SWAPXY
d.rowOffset = d.columnOffsetCfg
d.columnOffset = d.rowOffsetCfg
}
@@ -593,18 +666,8 @@ func (d *DeviceOf[T]) SetScrollArea(topFixedArea, bottomFixedArea int16) {
// The screen doesn't use the full 320 pixel height.
// Enlarge the bottom fixed area to fill the 320 pixel height, so that
// bottomFixedArea starts from the visible bottom of the screen.
//
// VSCRDEF/VSCRSADD always operate on physical frame memory rows (0-319),
// regardless of MADCTL. For rotations with MV set (90°/270°), CASET
// addresses physical rows due to row/column exchange, so the physical row
// offset is d.columnOffset (= rowOffsetCfg). For other rotations,
// d.rowOffset is the physical row offset.
physRowOffset := d.rowOffset
if d.rotation == drivers.Rotation90 || d.rotation == drivers.Rotation270 {
physRowOffset = d.columnOffset
}
topFixedArea += physRowOffset
bottomFixedArea += (320 - d.height) - physRowOffset
topFixedArea += d.rowOffset
bottomFixedArea += (320 - d.height) - d.rowOffset
}
if d.rotation == drivers.Rotation180 {
// The screen is rotated by 180°, so we have to switch the top and
@@ -623,20 +686,10 @@ func (d *DeviceOf[T]) SetScrollArea(topFixedArea, bottomFixedArea int16) {
// SetScroll sets the vertical scroll address of the display.
func (d *DeviceOf[T]) SetScroll(line int16) {
switch d.rotation {
case drivers.Rotation90:
// With MV set, hardware scroll operates on physical rows, which map to the
// visual X axis. Add the physical row offset (d.columnOffset = rowOffsetCfg)
// so that line=0 addresses the first visible physical row.
line = line + d.columnOffset
case drivers.Rotation180:
if d.rotation == drivers.Rotation180 {
// The screen is rotated by 180°, so we have to invert the scroll line
// (taking care of the RowOffset).
line = (319 - d.rowOffset) - line
case drivers.Rotation270:
// With MV+MY, physical rows map to the visual X axis in reverse direction.
// line=0 addresses the last physical row of the visible area.
line = (d.columnOffset + d.height - 1) - line
}
d.buf[0] = uint8(line >> 8)
d.buf[1] = uint8(line)
-6
View File
@@ -96,12 +96,6 @@ const (
SX127X_OPMODE_RX_SINGLE = uint8(0x06)
SX127X_OPMODE_CAD = uint8(0x07)
SX127X_OPMODE_LOW_FREQUENCY = uint8(0x4)
SX127X_OPMODE_MODULATION_MASK = uint8(0x60)
SX127X_OPMODE_MODULATION_FSK = uint8(0x0)
SX127X_OPMODE_MODULATION_OOK = uint8(0x20)
SX127X_LORA_MAC_PUBLIC_SYNCWORD = 0x34
SX127X_LORA_MAC_PRIVATE_SYNCWORD = 0x14
)
+11 -38
View File
@@ -25,9 +25,9 @@ type Device struct {
rstPin machine.Pin // GPIO for reset
radioEventChan chan lora.RadioEvent // Channel for Receiving events
loraConf lora.Config // Current Lora configuration
controller RadioController // to manage interrupts with the radio
controller RadioController // to manage interactions with the radio
deepSleep bool // Internal Sleep state
deviceType int // sx1272, sx1273, sx1276, sx1279 (defaults sx1276)
deviceType int // sx1261,sx1262,sx1268 (defaults sx1261)
spiTxBuf []byte // global Tx buffer to avoid heap allocations in interrupt
spiRxBuf []byte // global Rx buffer to avoid heap allocations in interrupt
}
@@ -65,11 +65,6 @@ func (d *Device) SetRadioController(rc RadioController) error {
return nil
}
// Specify device type (sx1272, sx1273, sx1276, sx1279)
func (d *Device) SetDeviceType(devType int) {
d.deviceType = devType
}
// Reset re-initialize the sx127x device
func (d *Device) Reset() {
d.rstPin.Low()
@@ -86,11 +81,9 @@ func (d *Device) DetectDevice() bool {
// ReadRegister reads register value
func (d *Device) ReadRegister(reg uint8) uint8 {
if d.controller != nil {
d.controller.SetNss(false)
}
d.controller.SetNss(false)
// Send register
//d.spiTxBuf = []byte{reg & 0x7f}
d.spiTxBuf = d.spiTxBuf[:0]
d.spiTxBuf = append(d.spiTxBuf, byte(reg&0x7f))
d.spi.Tx(d.spiTxBuf, nil)
@@ -98,19 +91,13 @@ func (d *Device) ReadRegister(reg uint8) uint8 {
d.spiRxBuf = d.spiRxBuf[:0]
d.spiRxBuf = append(d.spiRxBuf, 0)
d.spi.Tx(nil, d.spiRxBuf)
if d.controller != nil {
d.controller.SetNss(true)
}
d.controller.SetNss(true)
return d.spiRxBuf[0]
}
// WriteRegister writes value to register
func (d *Device) WriteRegister(reg uint8, value uint8) uint8 {
if d.controller != nil {
d.controller.SetNss(false)
}
d.controller.SetNss(false)
// Send register
d.spiTxBuf = d.spiTxBuf[:0]
d.spiTxBuf = append(d.spiTxBuf, byte(reg|0x80))
@@ -121,10 +108,7 @@ func (d *Device) WriteRegister(reg uint8, value uint8) uint8 {
d.spiRxBuf = d.spiRxBuf[:0]
d.spiRxBuf = append(d.spiRxBuf, 0)
d.spi.Tx(d.spiTxBuf, d.spiRxBuf)
if d.controller != nil {
d.controller.SetNss(true)
}
d.controller.SetNss(true)
return d.spiRxBuf[0]
}
@@ -135,20 +119,9 @@ func (d *Device) SetOpMode(mode uint8) {
d.WriteRegister(SX127X_REG_OP_MODE, new)
}
// SetOpModeLora changes the sx1276 mode to lora.
// SetOpMode changes the sx1276 mode
func (d *Device) SetOpModeLora() {
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)|SX127X_OPMODE_LORA)
}
// SetOpModeFsk changes the sx1276 mode to fsk/ook.
func (d *Device) SetOpModeFsk() {
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)&^SX127X_OPMODE_LORA)
}
// SetModulationType changes the modulation type (SX127X_OPMODE_MODULATION_FSK, SX127X_OPMODE_MODULATION_OOK)
func (d *Device) SetModulationType(typ uint8) {
cleared := d.ReadRegister(SX127X_REG_OP_MODE) &^ SX127X_OPMODE_MODULATION_MASK
d.WriteRegister(SX127X_REG_OP_MODE, cleared|typ)
d.WriteRegister(SX127X_REG_OP_MODE, SX127X_OPMODE_LORA)
}
// GetVersion returns hardware version of sx1276 chipset
@@ -271,9 +244,9 @@ func (d *Device) SetLowDataRateOptim(val uint8) {
// SetLowFrequencyModeOn enables Low Data Rate Optimization
func (d *Device) SetLowFrequencyModeOn(val bool) {
if val {
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)|SX127X_OPMODE_LOW_FREQUENCY)
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)|0x04)
} else {
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)&^SX127X_OPMODE_LOW_FREQUENCY)
d.WriteRegister(SX127X_REG_OP_MODE, d.ReadRegister(SX127X_REG_OP_MODE)&0xfb)
}
}
-290
View File
@@ -1,290 +0,0 @@
// Package unoqmatrix provides a driver for the UnoQMatrix LED matrix display.
//
// The UnoQMatrix is an 8x13 LED matrix display that can be controlled using a single pin.
// It uses a multiplexing technique to control the LEDs, which allows for a large number of LEDs to be controlled with fewer pins.
//
// This driver provides basic functionality to set individual pixels, clear the display, and refresh the display.
//
// Note: The UnoQMatrix does not support brightness control or color depth. Each pixel can only be turned on or off.
// Could it suppport brightness control by using PWM on the pin? To be investigated.
package unoqmatrix
import (
"image/color"
"time"
pin "tinygo.org/x/drivers/internal/pin"
)
type Config struct {
// Rotation of the LED matrix.
Rotation uint8
}
// Valid values:
//
// 0: regular orientation, (0 degree rotation)
// 1: 90 degree rotation clockwise
// 2: 180 degree rotation clockwise
// 3: 270 degree rotation clockwise
const (
RotationNormal = 0
Rotation90 = 1
Rotation180 = 2
Rotation270 = 3
)
const (
ledRows = 8
ledCols = 13
pixelRefreshDelay = 10 * time.Microsecond
)
// CharlieplexPin represents a pin used for charlieplexing.
// It must be able to drive high/low (output mode) and float (high-impedance/input mode).
//
// Example construction from a machine.Pin using the pin HAL pattern:
//
// var isOutput bool
// cp := unoqmatrix.CharlieplexPin{
// Set: pin.OutputFunc(func(level bool) {
// if !isOutput {
// p.Configure(machine.PinConfig{Mode: machine.PinOutput})
// isOutput = true
// }
// p.Set(level)
// }),
// Float: func() {
// if isOutput {
// p.Configure(machine.PinConfig{Mode: machine.PinInput})
// isOutput = false
// }
// },
// }
type CharlieplexPin struct {
Set pin.OutputFunc // Drive pin high (true) or low (false); auto-configures to output mode.
Float func() // Put pin into high-impedance (input) mode.
}
const numPins = 11
// Device represents the UnoQMatrix LED matrix display.
type Device struct {
pins [numPins]CharlieplexPin
buffer [ledRows][ledCols]color.RGBA
rotation uint8
}
// New returns a new unoqmatrix driver.
// The provided pins are the 11 charlieplex pins used to control the LED matrix.
func New(pins [numPins]CharlieplexPin) Device {
return Device{pins: pins}
}
// Configure sets up the device.
func (d *Device) Configure(cfg Config) {
d.SetRotation(cfg.Rotation)
}
// SetRotation changes the rotation of the LED matrix.
//
// Valid values for rotation:
//
// 0: regular orientation, (0 degree rotation)
// 1: 90 degree rotation clockwise
// 2: 180 degree rotation clockwise
// 3: 270 degree rotation clockwise
func (d *Device) SetRotation(rotation uint8) {
d.rotation = rotation % 4
}
// SetPixel sets the color of a specific pixel.
func (d *Device) SetPixel(x int16, y int16, c color.RGBA) {
d.buffer[y][x] = c
}
// GetPixel returns the color of a specific pixel.
func (d *Device) GetPixel(x int16, y int16) color.RGBA {
return d.buffer[y][x]
}
// Display sends the buffer (if any) to the screen.
// Only lights active (non-black) pixels, and resets only the 2 previously
// driven pins between LEDs instead of all 11, making each refresh cycle
// proportional to the number of lit LEDs.
func (d *Device) Display() error {
d.clearDisplay()
var lastIdx0, lastIdx1 uint8
hasLast := false
for row := 0; row < ledRows; row++ {
for col := 0; col < ledCols; col++ {
c := d.buffer[row][col]
if c.R == 0 && c.G == 0 && c.B == 0 {
continue
}
idx := row*ledCols + col
if idx < 0 || idx >= len(pinMapping) {
continue
}
// Float only the two pins that were driving the previous LED.
if hasLast {
d.pins[lastIdx0].Float()
d.pins[lastIdx1].Float()
}
hasLast = true
idx0 := pinMapping[idx][0]
idx1 := pinMapping[idx][1]
d.pins[idx0].Set.High()
d.pins[idx1].Set.Low()
lastIdx0 = idx0
lastIdx1 = idx1
time.Sleep(pixelRefreshDelay)
}
}
// Float the last driven LED.
if hasLast {
d.pins[lastIdx0].Float()
d.pins[lastIdx1].Float()
}
return nil
}
// ClearDisplay turns off all the LEDs on the display.
func (d *Device) ClearDisplay() {
for row := 0; row < ledRows; row++ {
for col := 0; col < ledCols; col++ {
d.buffer[row][col] = color.RGBA{0, 0, 0, 255}
}
}
}
// Size returns the current size of the display.
func (d *Device) Size() (w, h int16) {
return ledCols, ledRows
}
// pinMapping defines the mapping of LED indices to pin pairs. Each entry corresponds
// to an LED index (0-104) and contains the two pin numbers that need to be set to turn on that LED.
// based on https://github.com/arduino/ArduinoCore-zephyr/blob/main/loader/matrix.inc#L13
var pinMapping = [][2]uint8{
{0, 1}, // 0
{1, 0},
{0, 2},
{2, 0},
{1, 2},
{2, 1},
{0, 3},
{3, 0},
{1, 3},
{3, 1},
{2, 3}, // 10
{3, 2},
{0, 4},
{4, 0},
{1, 4},
{4, 1},
{2, 4},
{4, 2},
{3, 4},
{4, 3},
{0, 5}, // 20
{5, 0},
{1, 5},
{5, 1},
{2, 5},
{5, 2},
{3, 5},
{5, 3},
{4, 5},
{5, 4},
{0, 6}, // 30
{6, 0},
{1, 6},
{6, 1},
{2, 6},
{6, 2},
{3, 6},
{6, 3},
{4, 6},
{6, 4},
{5, 6}, // 40
{6, 5},
{0, 7},
{7, 0},
{1, 7},
{7, 1},
{2, 7},
{7, 2},
{3, 7},
{7, 3},
{4, 7}, // 50
{7, 4},
{5, 7},
{7, 5},
{6, 7},
{7, 6},
{0, 8},
{8, 0},
{1, 8},
{8, 1},
{2, 8}, // 60
{8, 2},
{3, 8},
{8, 3},
{4, 8},
{8, 4},
{5, 8},
{8, 5},
{6, 8},
{8, 6},
{7, 8}, // 70
{8, 7},
{0, 9},
{9, 0},
{1, 9},
{9, 1},
{2, 9},
{9, 2},
{3, 9},
{9, 3},
{4, 9}, // 80
{9, 4},
{5, 9},
{9, 5},
{6, 9},
{9, 6},
{7, 9},
{9, 7},
{8, 9},
{9, 8},
{0, 10}, // 90
{10, 0},
{1, 10},
{10, 1},
{2, 10},
{10, 2},
{3, 10},
{10, 3},
{4, 10},
{10, 4},
{5, 10}, // 100
{10, 5},
{6, 10},
{10, 6},
}
// clearDisplay turns off all the LEDs on the display by floating all pins.
func (d *Device) clearDisplay() {
for i := range d.pins {
d.pins[i].Float()
}
}
-325
View File
@@ -1,325 +0,0 @@
package unoqmatrix
import (
"image/color"
"testing"
pin "tinygo.org/x/drivers/internal/pin"
)
// pinState tracks the state of a mock charlieplex pin.
type pinState struct {
level bool // true=high, false=low
isOutput bool // true=output mode, false=floating (high-Z)
}
// mockPins creates 11 mock CharlieplexPins and returns them along with their observable state.
func mockPins() ([numPins]CharlieplexPin, *[numPins]pinState) {
var pins [numPins]CharlieplexPin
var states [numPins]pinState
for i := range pins {
idx := i // capture
pins[i] = CharlieplexPin{
Set: pin.OutputFunc(func(level bool) {
states[idx].isOutput = true
states[idx].level = level
}),
Float: func() {
states[idx].isOutput = false
states[idx].level = false
},
}
}
return pins, &states
}
func newTestDevice() (Device, *[numPins]pinState) {
pins, states := mockPins()
d := New(pins)
return d, states
}
func TestNew(t *testing.T) {
d, _ := newTestDevice()
w, h := d.Size()
if w != ledCols || h != ledRows {
t.Errorf("Size() = (%d, %d), want (%d, %d)", w, h, ledCols, ledRows)
}
}
func TestSize(t *testing.T) {
d, _ := newTestDevice()
w, h := d.Size()
if w != 13 {
t.Errorf("width = %d, want 13", w)
}
if h != 8 {
t.Errorf("height = %d, want 8", h)
}
}
func TestSetGetPixel(t *testing.T) {
d, _ := newTestDevice()
c := color.RGBA{R: 255, G: 128, B: 64, A: 255}
d.SetPixel(3, 2, c)
got := d.GetPixel(3, 2)
if got != c {
t.Errorf("GetPixel(3,2) = %v, want %v", got, c)
}
// Unset pixel should be zero-value.
got = d.GetPixel(0, 0)
if got != (color.RGBA{}) {
t.Errorf("GetPixel(0,0) = %v, want zero", got)
}
}
func TestClearDisplay(t *testing.T) {
d, _ := newTestDevice()
on := color.RGBA{R: 255, G: 255, B: 255, A: 255}
off := color.RGBA{A: 255}
d.SetPixel(0, 0, on)
d.SetPixel(5, 3, on)
d.ClearDisplay()
for y := int16(0); y < ledRows; y++ {
for x := int16(0); x < ledCols; x++ {
got := d.GetPixel(x, y)
if got != off {
t.Errorf("after ClearDisplay, GetPixel(%d,%d) = %v, want %v", x, y, got, off)
}
}
}
}
func TestSetRotation(t *testing.T) {
d, _ := newTestDevice()
tests := []struct {
input uint8
want uint8
}{
{0, 0},
{1, 1},
{2, 2},
{3, 3},
{4, 0}, // wraps
{7, 3}, // wraps
}
for _, tt := range tests {
d.SetRotation(tt.input)
if d.rotation != tt.want {
t.Errorf("SetRotation(%d): rotation = %d, want %d", tt.input, d.rotation, tt.want)
}
}
}
func TestConfigure(t *testing.T) {
d, _ := newTestDevice()
d.Configure(Config{Rotation: 2})
if d.rotation != 2 {
t.Errorf("Configure(Rotation:2): rotation = %d, want 2", d.rotation)
}
}
func TestDisplayEmptyBuffer(t *testing.T) {
d, states := newTestDevice()
err := d.Display()
if err != nil {
t.Fatalf("Display() error: %v", err)
}
// All pins should be floating after displaying an empty buffer.
for i, s := range states {
if s.isOutput {
t.Errorf("pin %d still in output mode after empty Display()", i)
}
}
}
func TestDisplaySinglePixel(t *testing.T) {
d, states := newTestDevice()
on := color.RGBA{R: 255, G: 255, B: 255, A: 255}
// LED index 0 -> pinMapping[0] = {0, 1}: pin 0 high, pin 1 low.
d.SetPixel(0, 0, on)
err := d.Display()
if err != nil {
t.Fatalf("Display() error: %v", err)
}
// After Display completes, all pins should be floating (last LED turned off).
for i, s := range states {
if s.isOutput {
t.Errorf("pin %d still in output mode after Display()", i)
}
}
}
func TestDisplayMultiplePixels(t *testing.T) {
d, states := newTestDevice()
on := color.RGBA{R: 255, G: 255, B: 255, A: 255}
d.SetPixel(0, 0, on) // idx 0 -> pins {0,1}
d.SetPixel(1, 0, on) // idx 1 -> pins {1,0}
d.SetPixel(2, 0, on) // idx 2 -> pins {0,2}
err := d.Display()
if err != nil {
t.Fatalf("Display() error: %v", err)
}
// All pins floating after display completes.
for i, s := range states {
if s.isOutput {
t.Errorf("pin %d still in output mode after Display()", i)
}
}
}
// pinEvent records a single pin action during Display().
type pinEvent struct {
pinIdx int
action string // "high", "low", or "float"
}
// traceDevice creates a device that records every pin event for verification.
func traceDevice() (Device, *[]pinEvent) {
var pins [numPins]CharlieplexPin
events := &[]pinEvent{}
for i := range pins {
idx := i
pins[i] = CharlieplexPin{
Set: pin.OutputFunc(func(level bool) {
action := "low"
if level {
action = "high"
}
*events = append(*events, pinEvent{pinIdx: idx, action: action})
}),
Float: func() {
*events = append(*events, pinEvent{pinIdx: idx, action: "float"})
},
}
}
d := New(pins)
return d, events
}
func TestDisplayDrivesCorrectPins(t *testing.T) {
d, events := traceDevice()
on := color.RGBA{R: 255, A: 255}
// Set pixel at (0,0) -> LED index 0 -> pinMapping[0] = {0, 1}.
d.SetPixel(0, 0, on)
d.Display()
// Expected sequence:
// 1. clearDisplay: float pins 0..10
// 2. Drive LED 0: pin 0 high, pin 1 low
// 3. Cleanup: float pin 0, float pin 1
// Find the high/low events (skip initial floats from clearDisplay).
var driveEvents []pinEvent
for _, e := range *events {
if e.action == "high" || e.action == "low" {
driveEvents = append(driveEvents, e)
}
}
if len(driveEvents) != 2 {
t.Fatalf("expected 2 drive events, got %d: %v", len(driveEvents), driveEvents)
}
if driveEvents[0].pinIdx != 0 || driveEvents[0].action != "high" {
t.Errorf("first drive event = %v, want pin 0 high", driveEvents[0])
}
if driveEvents[1].pinIdx != 1 || driveEvents[1].action != "low" {
t.Errorf("second drive event = %v, want pin 1 low", driveEvents[1])
}
}
func TestDisplaySkipsBlackPixels(t *testing.T) {
d, events := traceDevice()
on := color.RGBA{R: 255, A: 255}
// Only set one pixel in the middle of the matrix.
d.SetPixel(4, 1, on) // idx = 1*13+4 = 17 -> pinMapping[17] = {4,2}
d.Display()
var driveEvents []pinEvent
for _, e := range *events {
if e.action == "high" || e.action == "low" {
driveEvents = append(driveEvents, e)
}
}
// Should only drive one LED's worth of pin events.
if len(driveEvents) != 2 {
t.Fatalf("expected 2 drive events for 1 lit pixel, got %d", len(driveEvents))
}
if driveEvents[0].pinIdx != 4 || driveEvents[0].action != "high" {
t.Errorf("expected pin 4 high, got %v", driveEvents[0])
}
if driveEvents[1].pinIdx != 2 || driveEvents[1].action != "low" {
t.Errorf("expected pin 2 low, got %v", driveEvents[1])
}
}
func TestDisplayFloatsBetweenLEDs(t *testing.T) {
d, events := traceDevice()
on := color.RGBA{R: 255, A: 255}
d.SetPixel(0, 0, on) // idx 0 -> {0,1}
d.SetPixel(1, 0, on) // idx 1 -> {1,0}
d.Display()
// After the initial clearDisplay floats, the sequence for two LEDs should be:
// drive LED0 (pin0 high, pin1 low)
// float pin0, float pin1 (between LEDs)
// drive LED1 (pin1 high, pin0 low)
// float pin1, float pin0 (cleanup)
// Skip the initial 11 float events from clearDisplay.
postClear := (*events)[numPins:]
// Verify pin 0 and 1 are floated between the two LEDs.
foundFloatBetween := false
driveCount := 0
for _, e := range postClear {
if e.action == "high" || e.action == "low" {
driveCount++
}
// After the first pair of drive events, we should see floats before the next pair.
if driveCount == 2 && e.action == "float" {
foundFloatBetween = true
break
}
}
if !foundFloatBetween {
t.Error("expected float events between LED drives, found none")
}
}
func TestPinMappingLength(t *testing.T) {
expected := 104 // 8x13 matrix = 104 LEDs
if len(pinMapping) != expected {
t.Errorf("pinMapping has %d entries, want %d", len(pinMapping), expected)
}
}
func TestPinMappingIndicesInRange(t *testing.T) {
for i, pair := range pinMapping {
if pair[0] >= numPins {
t.Errorf("pinMapping[%d][0] = %d, exceeds numPins (%d)", i, pair[0], numPins)
}
if pair[1] >= numPins {
t.Errorf("pinMapping[%d][1] = %d, exceeds numPins (%d)", i, pair[1], numPins)
}
if pair[0] == pair[1] {
t.Errorf("pinMapping[%d] has same pin for both: %d", i, pair[0])
}
}
}
-36
View File
@@ -1,36 +0,0 @@
//go:build baremetal
package unoqmatrix
import (
"machine"
pin "tinygo.org/x/drivers/internal/pin"
)
// NewFromBasePin creates a Device from a base machine.Pin.
// It constructs 11 CharlieplexPin values from consecutive pins starting at basePin.
// Each pin lazily switches between output and input mode as needed.
func NewFromBasePin(basePin machine.Pin) Device {
var pins [numPins]CharlieplexPin
for i := range pins {
p := basePin + machine.Pin(i)
var isOutput bool
pins[i] = CharlieplexPin{
Set: pin.OutputFunc(func(level bool) {
if !isOutput {
p.Configure(machine.PinConfig{Mode: machine.PinOutput})
isOutput = true
}
p.Set(level)
}),
Float: func() {
if isOutput {
p.Configure(machine.PinConfig{Mode: machine.PinInput})
isOutput = false
}
},
}
}
return New(pins)
}
+1 -1
View File
@@ -2,4 +2,4 @@ package drivers
// Version returns a user-readable string showing the version of the drivers package for support purposes.
// Update this value before release of new version of software.
const Version = "0.35.0"
const Version = "0.34.0"
-465
View File
@@ -1,465 +0,0 @@
// Package epd2in9v2 implements a driver for the Waveshare 2.9in V2 black and white e-paper display.
//
// This is for the V2 device using the SSD1680 chipset. For the V1 device (using IL3820),
// use the epd2in9 package instead.
//
// Datasheet:
// https://files.waveshare.com/upload/7/79/2.9inch-e-paper-v2-specification.pdf
// https://cdn-learn.adafruit.com/assets/assets/000/097/631/original/SSD1680_Datasheet.pdf?1607625960
//
// Reference: https://github.com/waveshareteam/e-Paper/tree/master/RaspberryPi_JetsonNano/c/lib/e-Paper
package epd2in9v2 // import "tinygo.org/x/drivers/waveshare-epd/epd2in9v2"
import (
"image/color"
"machine"
"time"
"tinygo.org/x/drivers"
)
type Config struct {
Width int16
Height int16
Rotation Rotation
Speed Speed
Blocking bool
}
type Device struct {
bus drivers.SPI
cs machine.Pin
dc machine.Pin
rst machine.Pin
busy machine.Pin
width int16
height int16
buffer []uint8
bufferLength uint32
rotation Rotation
speed Speed
blocking bool
}
type Rotation uint8
type Speed uint8
// LUT for normal full refresh (~2s)
var lutDefault = [159]uint8{
0x80, 0x66, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0,
0x10, 0x66, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0,
0x80, 0x66, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0,
0x10, 0x66, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x14, 0x8, 0x0, 0x0, 0x0, 0x0, 0x1,
0xA, 0xA, 0x0, 0xA, 0xA, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x14, 0x8, 0x0, 0x1, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x0, 0x0, 0x0,
0x22, 0x17, 0x41, 0x0, 0x32, 0x36,
}
// LUT for fast full refresh (~1s)
var lutFast = [159]uint8{
0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x19, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x24, 0x42, 0x22, 0x22, 0x23, 0x32, 0x00, 0x00, 0x00,
0x22, 0x17, 0x41, 0xAE, 0x32, 0x38,
}
// LUT for partial refresh
var lutPartial = [159]uint8{
0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x80, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x40, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0A, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x0, 0x0, 0x0,
0x22, 0x17, 0x41, 0xB0, 0x32, 0x36,
}
// New returns a new epd2in9v2 driver. Pass in a fully configured SPI bus.
func New(bus drivers.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device {
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
rstPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
busyPin.Configure(machine.PinConfig{Mode: machine.PinInput})
return Device{
bus: bus,
cs: csPin,
dc: dcPin,
rst: rstPin,
busy: busyPin,
}
}
// Configure sets up the device.
func (d *Device) Configure(cfg Config) {
if cfg.Width != 0 {
d.width = cfg.Width
} else {
d.width = EPD_WIDTH
}
if cfg.Height != 0 {
d.height = cfg.Height
} else {
d.height = EPD_HEIGHT
}
d.rotation = cfg.Rotation
d.speed = cfg.Speed
d.blocking = cfg.Blocking
d.bufferLength = (uint32(d.width) * uint32(d.height)) / 8
d.buffer = make([]uint8, d.bufferLength)
for i := uint32(0); i < d.bufferLength; i++ {
d.buffer[i] = 0xFF
}
d.Reset()
time.Sleep(100 * time.Millisecond)
d.WaitUntilIdle()
d.SendCommand(SW_RESET)
d.WaitUntilIdle()
d.SendCommand(DRIVER_OUTPUT_CONTROL)
d.SendData(uint8((d.height - 1) & 0xFF))
d.SendData(uint8((d.height - 1) >> 8))
d.SendData(0x00)
d.SendCommand(DATA_ENTRY_MODE)
d.SendData(0x03)
d.setWindow(0, 0, d.width-1, d.height-1)
if cfg.Speed == SPEED_FAST {
d.SendCommand(BORDER_WAVEFORM_CONTROL)
d.SendData(0x05)
}
d.SendCommand(DISPLAY_UPDATE_CONTROL_1)
d.SendData(0x00)
d.SendData(0x80)
d.setCursor(0, 0)
d.WaitUntilIdle()
switch cfg.Speed {
case SPEED_FAST:
d.setLUTByHost(&lutFast)
default:
d.setLUTByHost(&lutDefault)
}
}
// HardwareReset resets the device via the RST pin.
func (d *Device) Reset() {
d.rst.High()
time.Sleep(10 * time.Millisecond)
d.rst.Low()
time.Sleep(2 * time.Millisecond)
d.rst.High()
time.Sleep(10 * time.Millisecond)
}
// SendCommand sends a command byte to the display.
func (d *Device) SendCommand(command uint8) {
d.dc.Low()
d.cs.Low()
d.bus.Transfer(command)
d.cs.High()
}
// SendData sends a data byte to the display.
func (d *Device) SendData(data uint8) {
d.dc.High()
d.cs.Low()
d.bus.Transfer(data)
d.cs.High()
}
// WaitUntilIdle waits until the display is ready.
// On SSD1680, BUSY pin is HIGH when busy, LOW when idle.
func (d *Device) WaitUntilIdle() {
for d.busy.Get() {
time.Sleep(50 * time.Millisecond)
}
time.Sleep(50 * time.Millisecond)
}
// IsBusy returns the busy status of the display.
func (d *Device) IsBusy() bool {
return d.busy.Get()
}
// SetPixel modifies the internal buffer in a single pixel.
// Uses color.RGBA where black (0,0,0) = black pixel, anything else = white pixel.
func (d *Device) SetPixel(x int16, y int16, c color.RGBA) {
x, y = d.xy(x, y)
if x < 0 || x >= d.width || y < 0 || y >= d.height {
return
}
byteIndex := (y * (d.width / 8)) + (x / 8)
if c.R == 0 && c.G == 0 && c.B == 0 {
d.buffer[byteIndex] &^= 0x80 >> uint8(x%8)
} else {
d.buffer[byteIndex] |= 0x80 >> uint8(x%8)
}
}
// Display sends the buffer to the screen.
func (d *Device) Display() error {
if d.blocking {
d.WaitUntilIdle()
}
d.setCursor(0, 0)
d.SendCommand(WRITE_RAM_BW)
for i := uint32(0); i < d.bufferLength; i++ {
d.SendData(d.buffer[i])
}
d.turnOnDisplay()
if d.blocking {
d.WaitUntilIdle()
}
return nil
}
// DisplayWithBase writes the buffer to both BW and RED RAM then refreshes.
// This is useful before partial updates to set the base image.
func (d *Device) DisplayWithBase() error {
if d.blocking {
d.WaitUntilIdle()
}
d.setCursor(0, 0)
d.SendCommand(WRITE_RAM_BW)
for i := uint32(0); i < d.bufferLength; i++ {
d.SendData(d.buffer[i])
}
d.setCursor(0, 0)
d.SendCommand(WRITE_RAM_RED)
for i := uint32(0); i < d.bufferLength; i++ {
d.SendData(d.buffer[i])
}
d.turnOnDisplay()
if d.blocking {
d.WaitUntilIdle()
}
return nil
}
// DisplayPartial performs a partial refresh of the display.
// Call DisplayWithBase first to set the base image before using partial updates.
func (d *Device) DisplayPartial() error {
d.rst.Low()
time.Sleep(1 * time.Millisecond)
d.rst.High()
time.Sleep(2 * time.Millisecond)
d.setLUT(&lutPartial)
d.SendCommand(OTP_SELECTION_CONTROL)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x40)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x00)
d.SendData(0x00)
d.SendCommand(BORDER_WAVEFORM_CONTROL)
d.SendData(0x80)
d.SendCommand(DISPLAY_UPDATE_CONTROL_2)
d.SendData(0xC0)
d.SendCommand(MASTER_ACTIVATION)
d.WaitUntilIdle()
d.setWindow(0, 0, d.width-1, d.height-1)
d.setCursor(0, 0)
d.SendCommand(WRITE_RAM_BW)
for i := uint32(0); i < d.bufferLength; i++ {
d.SendData(d.buffer[i])
}
d.turnOnDisplayPartial()
d.WaitUntilIdle()
return nil
}
// ClearDisplay erases the display.
func (d *Device) ClearDisplay() {
d.ClearBuffer()
d.Display()
}
// ClearBuffer sets the buffer to 0xFF (white).
func (d *Device) ClearBuffer() {
for i := uint32(0); i < d.bufferLength; i++ {
d.buffer[i] = 0xFF
}
}
// Size returns the current size of the display.
func (d *Device) Size() (w, h int16) {
if d.rotation == ROTATION_90 || d.rotation == ROTATION_270 {
return d.height, d.width
}
return d.width, d.height
}
// SetRotation changes the rotation (clock-wise) of the device.
func (d *Device) SetRotation(rotation Rotation) {
d.rotation = rotation
}
// SetBlocking changes the blocking flag of the device.
func (d *Device) SetBlocking(blocking bool) {
d.blocking = blocking
}
// SetSpeed changes the refresh speed and reconfigures the device.
func (d *Device) SetSpeed(speed Speed) {
d.Configure(Config{
Width: d.width,
Height: d.height,
Rotation: d.rotation,
Speed: speed,
Blocking: d.blocking,
})
}
// Sleep puts the display into deep sleep mode. A hardware reset is needed to wake it.
func (d *Device) Sleep() {
d.SendCommand(DEEP_SLEEP_MODE)
d.SendData(0x01)
time.Sleep(100 * time.Millisecond)
}
// PowerOff disables the display analog/clock. Lighter than Sleep.
func (d *Device) PowerOff() {
d.SendCommand(DISPLAY_UPDATE_CONTROL_2)
d.SendData(0x03)
d.SendCommand(MASTER_ACTIVATION)
d.WaitUntilIdle()
}
func (d *Device) xy(x, y int16) (int16, int16) {
switch d.rotation {
case NO_ROTATION:
return x, y
case ROTATION_90:
return d.width - y - 1, x
case ROTATION_180:
return d.width - x - 1, d.height - y - 1
case ROTATION_270:
return y, d.height - x - 1
}
return x, y
}
func (d *Device) setWindow(xStart, yStart, xEnd, yEnd int16) {
d.SendCommand(SET_RAM_X_ADDRESS)
d.SendData(uint8((xStart >> 3) & 0xFF))
d.SendData(uint8((xEnd >> 3) & 0xFF))
d.SendCommand(SET_RAM_Y_ADDRESS)
d.SendData(uint8(yStart & 0xFF))
d.SendData(uint8((yStart >> 8) & 0xFF))
d.SendData(uint8(yEnd & 0xFF))
d.SendData(uint8((yEnd >> 8) & 0xFF))
}
func (d *Device) setCursor(x, y int16) {
d.SendCommand(SET_RAM_X_COUNTER)
d.SendData(uint8(x & 0xFF))
d.SendCommand(SET_RAM_Y_COUNTER)
d.SendData(uint8(y & 0xFF))
d.SendData(uint8((y >> 8) & 0xFF))
}
func (d *Device) turnOnDisplay() {
d.SendCommand(DISPLAY_UPDATE_CONTROL_2)
d.SendData(0xC7)
d.SendCommand(MASTER_ACTIVATION)
d.WaitUntilIdle()
}
func (d *Device) turnOnDisplayPartial() {
d.SendCommand(DISPLAY_UPDATE_CONTROL_2)
d.SendData(0x0F)
d.SendCommand(MASTER_ACTIVATION)
d.WaitUntilIdle()
}
func (d *Device) setLUT(lut *[159]uint8) {
d.SendCommand(WRITE_LUT_REGISTER)
for i := 0; i < 153; i++ {
d.SendData(lut[i])
}
d.WaitUntilIdle()
}
func (d *Device) setLUTByHost(lut *[159]uint8) {
d.setLUT(lut)
d.SendCommand(END_OPTION)
d.SendData(lut[153])
d.SendCommand(GATE_DRIVING_VOLTAGE)
d.SendData(lut[154])
d.SendCommand(SOURCE_DRIVING_VOLTAGE)
d.SendData(lut[155])
d.SendData(lut[156])
d.SendData(lut[157])
d.SendCommand(WRITE_VCOM_REGISTER)
d.SendData(lut[158])
}
-50
View File
@@ -1,50 +0,0 @@
package epd2in9v2
// Commands from SSD1680 datasheet
const (
EPD_WIDTH = 128
EPD_HEIGHT = 296
DRIVER_OUTPUT_CONTROL = 0x01
GATE_DRIVING_VOLTAGE = 0x03
SOURCE_DRIVING_VOLTAGE = 0x04
DEEP_SLEEP_MODE = 0x10
DATA_ENTRY_MODE = 0x11
SW_RESET = 0x12
MASTER_ACTIVATION = 0x20
DISPLAY_UPDATE_CONTROL_1 = 0x21
DISPLAY_UPDATE_CONTROL_2 = 0x22
WRITE_RAM_BW = 0x24
WRITE_RAM_RED = 0x26
VCOM_SENSE = 0x28
VCOM_SENSE_DURATION = 0x29
PROGRAM_VCOM_OTP = 0x2A
WRITE_VCOM_CONTROL = 0x2B
WRITE_VCOM_REGISTER = 0x2C
OTP_READ_DISPLAY_OPTION = 0x2D
USER_ID_READ = 0x2E
PROGRAM_WS_OTP = 0x30
LOAD_WS_OTP = 0x31
WRITE_LUT_REGISTER = 0x32
PROGRAM_OTP_SELECTION = 0x36
OTP_SELECTION_CONTROL = 0x37
WRITE_USER_ID = 0x38
OTP_PROGRAM_MODE = 0x39
BORDER_WAVEFORM_CONTROL = 0x3C
END_OPTION = 0x3F
SET_RAM_X_ADDRESS = 0x44
SET_RAM_Y_ADDRESS = 0x45
SET_RAM_X_COUNTER = 0x4E
SET_RAM_Y_COUNTER = 0x4F
SET_ANALOG_BLOCK_CONTROL = 0x74
SET_DIGITAL_BLOCK_CONTROL = 0x7E
NO_ROTATION Rotation = 0
ROTATION_90 Rotation = 1
ROTATION_180 Rotation = 2
ROTATION_270 Rotation = 3
SPEED_DEFAULT Speed = 0
SPEED_FAST Speed = 1
SPEED_PARTIAL Speed = 2
)
+22 -41
View File
@@ -1,7 +1,4 @@
// Package ws2812 implements a driver for WS2812 and SK6812 RGB LED strips.
//
// On most platforms NewWS2812 uses bit-banging.
// On RP2040/RP2350 it uses PIO for hardware-timed control.
package ws2812 // import "tinygo.org/x/drivers/ws2812"
//go:generate go run gen-ws2812.go -arch=cortexm 16 48 64 120 125 150 168 200
@@ -18,8 +15,7 @@ var errUnknownClockSpeed = errors.New("ws2812: unknown CPU clock speed")
// Device wraps a pin object for an easy driver interface.
type Device struct {
Pin machine.Pin
brightness uint8
writeColorFunc func(Device, []color.RGBA, uint8) error
writeColorFunc func(Device, []color.RGBA) error
}
// deprecated, use NewWS2812 or NewSK6812 depending on which device you want.
@@ -28,28 +24,24 @@ func New(pin machine.Pin) Device {
return NewWS2812(pin)
}
// NewWS2812 returns a new WS2812(RGB) driver.
// On RP2040/RP2350, it uses PIO for hardware-timed control.
// On other platforms, you must configure the pin as output before calling this.
// New returns a new WS2812(RGB) driver.
// It does not touch the pin object: you have
// to configure it as an output pin before calling New.
func NewWS2812(pin machine.Pin) Device {
return newWS2812Device(pin)
}
// NewSK6812 returns a new SK6812W/RGBW driver (4 channels, GRBW order, 32-bit protocol), for the 3 channels version use NewWS2812
// Use this for SK6812W strips that have a dedicated white channel controlled via color.A.
// It does not touch the pin object: you have to configure it as an output pin before
// calling this.
func NewSK6812(pin machine.Pin) Device {
return Device{
Pin: pin,
brightness: 255,
writeColorFunc: writeColorsRGBA,
writeColorFunc: writeColorsRGB,
}
}
// SetBrightness sets the global brightness (0-255).
func (d *Device) SetBrightness(b uint8) {
d.brightness = b
// New returns a new SK6812(RGBA) driver.
// It does not touch the pin object: you have
// to configure it as an output pin before calling New.
func NewSK6812(pin machine.Pin) Device {
return Device{
Pin: pin,
writeColorFunc: writeColorsRGBA,
}
}
// Write the raw bitstring out using the WS2812 protocol.
@@ -63,35 +55,24 @@ func (d Device) Write(buf []byte) (n int, err error) {
// Write the given color slice out using the WS2812 protocol.
// Colors are sent out in the usual GRB(A) format.
func (d Device) WriteColors(buf []color.RGBA) (err error) {
return d.writeColorFunc(d, buf, d.brightness)
return d.writeColorFunc(d, buf)
}
func writeColorsRGB(d Device, buf []color.RGBA, brightness uint8) (err error) {
func writeColorsRGB(d Device, buf []color.RGBA) (err error) {
for _, color := range buf {
r, g, b := applyBrightness(color, brightness)
d.WriteByte(g) // green
d.WriteByte(r) // red
err = d.WriteByte(b) // blue
d.WriteByte(color.G) // green
d.WriteByte(color.R) // red
err = d.WriteByte(color.B) // blue
}
return
}
func writeColorsRGBA(d Device, buf []color.RGBA, brightness uint8) (err error) {
func writeColorsRGBA(d Device, buf []color.RGBA) (err error) {
for _, color := range buf {
r, g, b := applyBrightness(color, brightness)
d.WriteByte(g) // green
d.WriteByte(r) // red
d.WriteByte(b) // blue
d.WriteByte(color.G) // green
d.WriteByte(color.R) // red
d.WriteByte(color.B) // blue
err = d.WriteByte(color.A) // alpha
}
return
}
// applyBrightness scales a color by the brightness value.
func applyBrightness(c color.RGBA, brightness uint8) (r, g, b uint8) {
r = uint8((uint16(c.R) * uint16(brightness)) >> 8)
g = uint8((uint16(c.G) * uint16(brightness)) >> 8)
b = uint8((uint16(c.B) * uint16(brightness)) >> 8)
return
}
-10
View File
@@ -1,10 +0,0 @@
//go:build !rp2040 && !rp2350
package ws2812
import "machine"
// newWS2812Device creates a WS2812 device using the bit-bang driver.
func newWS2812Device(pin machine.Pin) Device {
return Device{Pin: pin, brightness: 255, writeColorFunc: writeColorsRGB}
}
-35
View File
@@ -1,35 +0,0 @@
//go:build rp2040 || rp2350
package ws2812
import (
"image/color"
"machine"
pio "github.com/tinygo-org/pio/rp2-pio"
"github.com/tinygo-org/pio/rp2-pio/piolib"
)
// newWS2812Device creates a WS2812 device using PIO for hardware-timed control.
// If PIO initialization fails, it falls back to the bit-bang driver.
func newWS2812Device(pin machine.Pin) Device {
sm, err := pio.PIO0.ClaimStateMachine()
if err != nil {
return Device{Pin: pin, brightness: 255, writeColorFunc: writeColorsRGB}
}
ws, err := piolib.NewWS2812B(sm, pin)
if err != nil {
return Device{Pin: pin, brightness: 255, writeColorFunc: writeColorsRGB}
}
return Device{
Pin: pin,
brightness: 255,
writeColorFunc: func(_ Device, buf []color.RGBA, brightness uint8) error {
for _, c := range buf {
r, g, b := applyBrightness(c, brightness)
ws.PutRGB(r, g, b)
}
return nil
},
}
}