Compare commits

..

28 Commits

Author SHA1 Message Date
deadprogram dcf53ac04a revision: modify proposed pin HAL.
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-09-16 20:33:50 +02:00
deadprogram f55c0b1853 fix: correct smoke tests for Adafruit Seesaw
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-09-16 19:16:01 +02:00
JP Hastings-Spital acc0d47b72 feat: add support for seesaw encoders
Adds the necessary function addresses for reading and writing encoders on a seesaw.
Also provides two helper functions to make this easier.
2025-09-16 19:16:01 +02:00
Russel Hunter Yukawa 9e1d8f6998 Fix gps time calculation (#785)
* Change test case to match the date patterns where the bug reproduces
* Fix RMC date and time calculation
2025-09-16 19:16:01 +02:00
Bryan Souza 4d81aa4787 added support for LSM303DLHC e-Compass; (#783)
fixed the spelling in the Connection error message; Initial support for LSM303DLHC added;
Added LSM303DLHC to smoketest and added an example;
Removed unnecessary comments;
fixed format error;
squashed and ready for merge;
2025-09-16 19:16:01 +02:00
Artur Nasyrov 24a9d7dcc9 Add ens160 i2c driver
Driver for ENS160 sensor:
https://www.sciosense.com/wp-content/uploads/2023/12/ENS160-Datasheet.pdf
2025-09-16 19:16:01 +02:00
Ayke van Laethem 9717f365d9 ws2812: add RP2350 support
Adding 150MHz support for the RP2350
2025-09-16 19:16:01 +02:00
Yurii Soldak e61269cdc0 ssd1306: avoid unnecessary heap allocations (#767)
* ssd1306: avoid unnecessary heap allocations

* ssd1306: extract i2c and spi bus implementations

* ssd1306: refactor tests -- show fps and heap usage

* ssd1306: bring back the lost exported methods

* Adjust examples

* Fix smoketests for ssd1306
2025-09-16 19:16:01 +02:00
JP Hastings-Spital 6e1e9b75b8 feat: allow gps init with address
Adafruit's Mini GPS PA1010D Module works with this device driver, but requires 0x10 as the address, rather than 0x42.

This change allows the device to be initialised with whatever i2c address is needed, while maintaining backward compatibility.

Adds new constants to allow easy configuration of both the ublox device and the PA1010D.
2025-09-16 19:16:01 +02:00
Yurii Soldak b7be85a96a lsm6ds3tr: avoid unnecessary heap allocations (#766)
* lsm6ds3tr: avoid unnecessary heap allocations
* lsm6ds3tr: use helper functions, for readability
* lsm6ds3tr: return slice of the internal buffer on readBytes
2025-09-16 19:16:01 +02:00
Ron Evans 1d618b4729 Revert "add regmap package to facilitate heapless driver development (#768)" (#776)
This reverts commit 80356fd9d9.
2025-09-16 19:16:01 +02:00
Patricio Whittingslow 40784df446 add regmap package to facilitate heapless driver development (#768) 2025-09-16 19:16:01 +02:00
deadprogram c8788ee4a1 all: updates for drivers release v0.32.0
Signed-off-by: deadprogram <ron@hybridgroup.com>
2025-09-16 19:16:01 +02:00
soypat adfc8def7b add driver design pointer to CONTRIBUTING.md 2025-09-16 19:16:01 +02:00
Hikmatulloh Hari Mukti 5b9be516c5 bmp280: remove alloc on read sensor data 2025-09-16 19:16:01 +02:00
Leon Matthews 462a0de10a ws2812: add 200MHz support for the Cortex-M0/rp2040 2025-09-16 19:16:01 +02:00
Mateusz Nowak ad49c0d0ca fix: remove time.Sleep from SSD1306 SPI transfer code 2025-09-16 19:16:01 +02:00
Craig Swank 673367c317 tmc2209 bug fixes (#755)
* Make write buffer big enough for crc
* crc according to datasheet
* fix build
* a correct crc func already exists
2025-09-16 19:16:01 +02:00
Patricio Whittingslow 8b6e8c81e3 rename busy fields to isBusy 2025-09-16 09:49:45 -03:00
Patricio Whittingslow 1f37a1398c missed high or low ~voltage~ level 2025-09-16 09:31:11 -03:00
Patricio Whittingslow 8d3cac8322 apply @gen2thomas suggestions 2025-09-16 09:26:00 -03:00
Patricio Whittingslow 3cd6afb84c pins.go -> pin.go 2025-09-07 17:13:50 -03:00
soypat db544f4ca7 bugfix: output misconfigured 2025-07-09 12:14:14 -03:00
soypat 9fb57e22fb fix pullups not available on fe310 2025-07-09 12:04:37 -03:00
soypat 3681452097 finish rewrites! 2025-07-08 21:11:46 -03:00
soypat 8f0fbaa945 more drivers are now cross platform 2025-07-02 22:03:58 -03:00
soypat f3945b1d58 apply suggestions from team 2025-04-30 15:18:21 -03:00
soypat 06e4c0267f add PinInput and PinOutput HAL 2025-04-08 17:08:08 -03:00
54 changed files with 748 additions and 1576 deletions
-25
View File
@@ -1,28 +1,3 @@
0.33.0
---
- **new devices**
- **ens160**
- Add ens160 i2c driver
- **lsm303dlhc**
- added support for LSM303DLHC e-Compass; (#783)
- **seesaw**
- add support for Adafruit Seesaw encoders
- **enhancements**
- **ws2812**
- add RP2350 support
- **ssd1306**
- avoid unnecessary heap allocations (#767)
- **gps**
- allow gps init with address
- **lsm6ds3tr**
- avoid unnecessary heap allocations (#766)
- **bugfixes**
- **gps**
- Fix gps time calculation (#785)
0.32.0 0.32.0
--- ---
- **enhancements** - **enhancements**
+6 -3
View File
@@ -5,9 +5,9 @@ package apa102 // import "tinygo.org/x/drivers/apa102"
import ( import (
"image/color" "image/color"
"machine"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
const ( const (
@@ -37,8 +37,11 @@ func New(b drivers.SPI) *Device {
// NewSoftwareSPI returns a new APA102 driver that will use a software based // NewSoftwareSPI returns a new APA102 driver that will use a software based
// implementation of the SPI protocol. // implementation of the SPI protocol.
func NewSoftwareSPI(sckPin, sdoPin machine.Pin, delay uint32) *Device { func NewSoftwareSPI(sckPin, sdoPin pin.Output, delay uint32) *Device {
return New(&bbSPI{SCK: sckPin, SDO: sdoPin, Delay: delay}) return New(&bbSPI{SCK: sckPin.Set, SDO: sdoPin.Set, Delay: delay, configurePins: func() {
pin.ConfigureOutput(sckPin)
pin.ConfigureOutput(sdoPin)
}})
} }
// WriteColors writes the given RGBA color slice out using the APA102 protocol. // WriteColors writes the given RGBA color slice out using the APA102 protocol.
+11 -6
View File
@@ -1,6 +1,8 @@
package apa102 package apa102
import "machine" import (
"tinygo.org/x/drivers/internal/pin"
)
// bbSPI is a dumb bit-bang implementation of SPI protocol that is hardcoded // bbSPI is a dumb bit-bang implementation of SPI protocol that is hardcoded
// to mode 0 and ignores trying to receive data. Just enough for the APA102. // to mode 0 and ignores trying to receive data. Just enough for the APA102.
@@ -8,15 +10,18 @@ import "machine"
// most purposes other than the APA102 package. It might be desirable to make // most purposes other than the APA102 package. It might be desirable to make
// this more generic and include it in the TinyGo "machine" package instead. // this more generic and include it in the TinyGo "machine" package instead.
type bbSPI struct { type bbSPI struct {
SCK machine.Pin SCK pin.OutputFunc
SDO machine.Pin SDO pin.OutputFunc
Delay uint32 Delay uint32
configurePins func()
} }
// Configure sets up the SCK and SDO pins as outputs and sets them low // Configure sets up the SCK and SDO pins as outputs and sets them low
func (s *bbSPI) Configure() { func (s *bbSPI) Configure() {
s.SCK.Configure(machine.PinConfig{Mode: machine.PinOutput}) if s.configurePins == nil {
s.SDO.Configure(machine.PinConfig{Mode: machine.PinOutput}) panic(pin.ErrConfigBeforeInstantiated)
}
s.configurePins()
s.SCK.Low() s.SCK.Low()
s.SDO.Low() s.SDO.Low()
if s.Delay == 0 { if s.Delay == 0 {
+30 -23
View File
@@ -1,31 +1,35 @@
package bmi160 package bmi160
import ( import (
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
// DeviceSPI is the SPI interface to a BMI160 accelerometer/gyroscope. There is // DeviceSPI is the SPI interface to a BMI160 accelerometer/gyroscope. There is
// also an I2C interface, but it is not yet supported. // also an I2C interface, but it is not yet supported.
type DeviceSPI struct { type DeviceSPI struct {
// Chip select pin // Chip select pin
CSB machine.Pin csb pin.OutputFunc
buf [7]byte buf [7]byte
// SPI bus (requires chip select to be usable). // SPI bus (requires chip select to be usable).
Bus drivers.SPI bus drivers.SPI
configurePins func()
} }
// NewSPI returns a new device driver. The pin and SPI interface are not // NewSPI returns a new device driver. The pin and SPI interface are not
// touched, provide a fully configured SPI object and call Configure to start // touched, provide a fully configured SPI object and call Configure to start
// using this device. // using this device.
func NewSPI(csb machine.Pin, spi drivers.SPI) *DeviceSPI { func NewSPI(csb pin.Output, spi drivers.SPI) *DeviceSPI {
return &DeviceSPI{ return &DeviceSPI{
CSB: csb, // chip select csb: csb.Set, // chip select
Bus: spi, bus: spi,
configurePins: func() {
pin.ConfigureOutput(csb)
},
} }
} }
@@ -33,8 +37,11 @@ func NewSPI(csb machine.Pin, spi drivers.SPI) *DeviceSPI {
// configures the BMI160, but it does not configure the SPI interface (it is // configures the BMI160, but it does not configure the SPI interface (it is
// assumed to be up and running). // assumed to be up and running).
func (d *DeviceSPI) Configure() error { func (d *DeviceSPI) Configure() error {
d.CSB.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.configurePins == nil {
d.CSB.High() return pin.ErrConfigBeforeInstantiated
}
d.configurePins()
d.csb.High()
// The datasheet recommends doing a register read from address 0x7F to get // The datasheet recommends doing a register read from address 0x7F to get
// SPI communication going: // SPI communication going:
@@ -86,9 +93,9 @@ func (d *DeviceSPI) ReadTemperature() (temperature int32, err error) {
data[0] = 0x80 | reg_TEMPERATURE_0 data[0] = 0x80 | reg_TEMPERATURE_0
data[1] = 0 data[1] = 0
data[2] = 0 data[2] = 0
d.CSB.Low() d.csb.Low()
err = d.Bus.Tx(data, data) err = d.bus.Tx(data, data)
d.CSB.High() d.csb.High()
if err != nil { if err != nil {
return return
} }
@@ -123,9 +130,9 @@ func (d *DeviceSPI) ReadAcceleration() (x int32, y int32, z int32, err error) {
for i := 1; i < len(data); i++ { for i := 1; i < len(data); i++ {
data[i] = 0 data[i] = 0
} }
d.CSB.Low() d.csb.Low()
err = d.Bus.Tx(data, data) err = d.bus.Tx(data, data)
d.CSB.High() d.csb.High()
if err != nil { if err != nil {
return return
} }
@@ -153,9 +160,9 @@ func (d *DeviceSPI) ReadRotation() (x int32, y int32, z int32, err error) {
for i := 1; i < len(data); i++ { for i := 1; i < len(data); i++ {
data[i] = 0 data[i] = 0
} }
d.CSB.Low() d.csb.Low()
err = d.Bus.Tx(data, data) err = d.bus.Tx(data, data)
d.CSB.High() d.csb.High()
if err != nil { if err != nil {
return return
} }
@@ -201,9 +208,9 @@ func (d *DeviceSPI) readRegister(address uint8) uint8 {
data := d.buf[:2] data := d.buf[:2]
data[0] = 0x80 | address data[0] = 0x80 | address
data[1] = 0 data[1] = 0
d.CSB.Low() d.csb.Low()
d.Bus.Tx(data, data) d.bus.Tx(data, data)
d.CSB.High() d.csb.High()
return data[1] return data[1]
} }
@@ -217,7 +224,7 @@ func (d *DeviceSPI) writeRegister(address, data uint8) {
buf[0] = address buf[0] = address
buf[1] = data buf[1] = data
d.CSB.Low() d.csb.Low()
d.Bus.Tx(buf, buf) d.bus.Tx(buf, buf)
d.CSB.High() d.csb.High()
} }
+7 -7
View File
@@ -2,22 +2,22 @@
package buzzer // import "tinygo.org/x/drivers/buzzer" package buzzer // import "tinygo.org/x/drivers/buzzer"
import ( import (
"machine"
"time" "time"
"tinygo.org/x/drivers/internal/pin"
) )
// Device wraps a GPIO connection to a buzzer. // Device wraps a GPIO connection to a buzzer.
type Device struct { type Device struct {
pin machine.Pin pin pin.OutputFunc
High bool High bool
BPM float64 BPM float64
} }
// New returns a new buzzer driver given which pin to use // New returns a new buzzer driver given which pin to use
func New(pin machine.Pin) Device { func New(pin pin.Output) Device {
return Device{ return Device{
pin: pin, pin: pin.Set,
High: false, High: false,
BPM: 96.0, BPM: 96.0,
} }
@@ -25,14 +25,14 @@ func New(pin machine.Pin) Device {
// On sets the buzzer to a high state. // On sets the buzzer to a high state.
func (l *Device) On() (err error) { func (l *Device) On() (err error) {
l.pin.Set(true) l.pin.High()
l.High = true l.High = true
return return
} }
// Off sets the buzzer to a low state. // Off sets the buzzer to a low state.
func (l *Device) Off() (err error) { func (l *Device) Off() (err error) {
l.pin.Set(false) l.pin.Low()
l.High = false l.High = false
return return
} }
+6 -69
View File
@@ -2,9 +2,9 @@
package easystepper // import "tinygo.org/x/drivers/easystepper" package easystepper // import "tinygo.org/x/drivers/easystepper"
import ( import (
"errors"
"machine"
"time" "time"
"tinygo.org/x/drivers/internal/pin"
) )
// StepMode determines the coil sequence used to perform a single step // StepMode determines the coil sequence used to perform a single step
@@ -30,28 +30,10 @@ func (sm StepMode) stepCount() uint {
} }
} }
// DeviceConfig contains the configuration data for a single easystepper driver
type DeviceConfig struct {
// Pin1 ... Pin4 determines the pins to configure and use for the device
Pin1, Pin2, Pin3, Pin4 machine.Pin
// StepCount is the number of steps required to perform a full revolution of the stepper motor
StepCount uint
// RPM determines the speed of the stepper motor in 'Revolutions per Minute'
RPM uint
// Mode determines the coil sequence used to perform a single step
Mode StepMode
}
// DualDeviceConfig contains the configuration data for a dual easystepper driver
type DualDeviceConfig struct {
DeviceConfig
// Pin5 ... Pin8 determines the pins to configure and use for the second device
Pin5, Pin6, Pin7, Pin8 machine.Pin
}
// Device holds the pins and the delay between steps // Device holds the pins and the delay between steps
type Device struct { type Device struct {
pins [4]machine.Pin pins [4]pin.OutputFunc
config func()
stepDelay time.Duration stepDelay time.Duration
stepNumber uint8 stepNumber uint8
stepMode StepMode stepMode StepMode
@@ -62,51 +44,6 @@ type DualDevice struct {
devices [2]*Device devices [2]*Device
} }
// New returns a new single easystepper driver given a DeviceConfig
func New(config DeviceConfig) (*Device, error) {
if config.StepCount == 0 || config.RPM == 0 {
return nil, errors.New("config.StepCount and config.RPM must be > 0")
}
return &Device{
pins: [4]machine.Pin{config.Pin1, config.Pin2, config.Pin3, config.Pin4},
stepDelay: time.Second * 60 / time.Duration((config.StepCount * config.RPM)),
stepMode: config.Mode,
}, nil
}
// Configure configures the pins of the Device
func (d *Device) Configure() {
for _, pin := range d.pins {
pin.Configure(machine.PinConfig{Mode: machine.PinOutput})
}
}
// NewDual returns a new dual easystepper driver given 8 pins, number of steps and rpm
func NewDual(config DualDeviceConfig) (*DualDevice, error) {
// Create the first device
dev1, err := New(config.DeviceConfig)
if err != nil {
return nil, err
}
// Create the second device
config.DeviceConfig.Pin1 = config.Pin5
config.DeviceConfig.Pin2 = config.Pin6
config.DeviceConfig.Pin3 = config.Pin7
config.DeviceConfig.Pin4 = config.Pin8
dev2, err := New(config.DeviceConfig)
if err != nil {
return nil, err
}
// Return composite dual device
return &DualDevice{devices: [2]*Device{dev1, dev2}}, nil
}
// Configure configures the pins of the DualDevice
func (d *DualDevice) Configure() {
d.devices[0].Configure()
d.devices[1].Configure()
}
// Move rotates the motor the number of given steps // Move rotates the motor the number of given steps
// (negative steps will rotate it the opposite direction) // (negative steps will rotate it the opposite direction)
func (d *Device) Move(steps int32) { func (d *Device) Move(steps int32) {
@@ -125,8 +62,8 @@ func (d *Device) Move(steps int32) {
// Off turns off all motor pins // Off turns off all motor pins
func (d *Device) Off() { func (d *Device) Off() {
for _, pin := range d.pins { for _, p := range d.pins {
pin.Low() p.Low()
} }
} }
+29
View File
@@ -0,0 +1,29 @@
package easystepper
import (
"errors"
"time"
"tinygo.org/x/drivers/internal/pin"
)
func NewCrossPlatform(stepcount, rpm uint, mode StepMode, pins [4]pin.Output) (*Device, error) {
if stepcount == 0 || rpm == 0 {
return nil, errors.New("zero rpm and/or stepcount")
}
var ps [4]pin.OutputFunc
for i := range pins {
if pins[i] == nil {
return nil, errors.New("nil pin")
}
ps[i] = pins[i].Set
}
d := &Device{
pins: ps,
stepDelay: time.Second * 60 / time.Duration((stepcount * rpm)),
stepMode: mode,
config: func() {},
}
return d, nil
}
+82
View File
@@ -0,0 +1,82 @@
//go:build baremetal
package easystepper
import (
"errors"
"machine"
"time"
"tinygo.org/x/drivers/internal/pin"
)
// New returns a new single easystepper driver given a DeviceConfig
func New(config DeviceConfig) (*Device, error) {
if config.StepCount == 0 || config.RPM == 0 {
return nil, errors.New("config.StepCount and config.RPM must be > 0")
}
return &Device{
pins: [4]pin.OutputFunc{config.Pin1.Set, config.Pin2.Set, config.Pin3.Set, config.Pin4.Set},
stepDelay: time.Second * 60 / time.Duration((config.StepCount * config.RPM)),
stepMode: config.Mode,
config: func() {
pin.ConfigureOutput(config.Pin1)
pin.ConfigureOutput(config.Pin2)
pin.ConfigureOutput(config.Pin3)
pin.ConfigureOutput(config.Pin4)
},
}, nil
}
// Configure configures the pins of the Device
func (d *Device) Configure() {
if d.config == nil {
panic(pin.ErrConfigBeforeInstantiated)
}
d.config()
}
// Configure configures the pins of the DualDevice
func (d *DualDevice) Configure() {
d.devices[0].Configure()
d.devices[1].Configure()
}
// NewDual returns a new dual easystepper driver given 8 pins, number of steps and rpm
func NewDual(config DualDeviceConfig) (*DualDevice, error) {
// Create the first device
dev1, err := New(config.DeviceConfig)
if err != nil {
return nil, err
}
// Create the second device
config.DeviceConfig.Pin1 = config.Pin5
config.DeviceConfig.Pin2 = config.Pin6
config.DeviceConfig.Pin3 = config.Pin7
config.DeviceConfig.Pin4 = config.Pin8
dev2, err := New(config.DeviceConfig)
if err != nil {
return nil, err
}
// Return composite dual device
return &DualDevice{devices: [2]*Device{dev1, dev2}}, nil
}
// DeviceConfig contains the configuration data for a single easystepper driver
type DeviceConfig struct {
// Pin1 ... Pin4 determines the pins to configure and use for the device
Pin1, Pin2, Pin3, Pin4 machine.Pin
// StepCount is the number of steps required to perform a full revolution of the stepper motor
StepCount uint
// RPM determines the speed of the stepper motor in 'Revolutions per Minute'
RPM uint
// Mode determines the coil sequence used to perform a single step
Mode StepMode
}
// DualDeviceConfig contains the configuration data for a dual easystepper driver
type DualDeviceConfig struct {
DeviceConfig
// Pin5 ... Pin8 determines the pins to configure and use for the second device
Pin5, Pin6, Pin7, Pin8 machine.Pin
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build tinygo && (rp2040 || rp2350 || stm32 || k210 || esp32c3 || nrf || sam || (avr && (atmega328p || atmega328pb))) //go:build tinygo && (rp2040 || stm32 || k210 || esp32c3 || nrf || sam || (avr && (atmega328p || atmega328pb)))
// Implementation based on: // Implementation based on:
// https://gist.github.com/aykevl/3fc1683ed77bb0a9c07559dfe857304a // https://gist.github.com/aykevl/3fc1683ed77bb0a9c07559dfe857304a
-49
View File
@@ -1,49 +0,0 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/honeyhsc"
)
// Data taken from https://github.com/rodan/honeywell_hsc_ssc_i2c/blob/master/hsc_ssc_i2c.cpp
// these defaults are valid for the HSCMRNN030PA2A3 chip
const (
i2cAddress = 0x28
// 10%
outputMinimum = 0x666
// 90% of 2^14 - 1
outputMax = 0x399A
// min is 0 for sensors that give absolute values
pressureMin = 0
// 30psi (and we want results in millipascals)
// pressureMax = 206842.7
pressureMax = 206843 * 1000
)
func main() {
bus := machine.I2C0
err := bus.Configure(machine.I2CConfig{
Frequency: 400_000, // 100kHz minimum and 400kHz I2C maximum clock. 50 to 800 for SPI.
SDA: machine.I2C0_SDA_PIN,
SCL: machine.I2C0_SCL_PIN,
})
if err != nil {
panic(err.Error())
}
sensor := honeyhsc.NewDevI2C(bus, i2cAddress, outputMinimum, outputMax, pressureMin, pressureMax)
for {
time.Sleep(time.Second)
const measuremask = drivers.Pressure | drivers.Temperature
err := sensor.Update(measuremask)
if err != nil {
println("error updating measurements:", err.Error())
continue
}
P := sensor.Pressure()
T := sensor.Temperature()
println("pressure:", P, "temperature:", T)
}
}
+3 -12
View File
@@ -14,18 +14,9 @@ func main() {
i2c.Configure(machine.I2CConfig{SCL: machine.SCL1_PIN, SDA: machine.SDA1_PIN}) i2c.Configure(machine.I2CConfig{SCL: machine.SCL1_PIN, SDA: machine.SDA1_PIN})
accel := lis3dh.New(i2c) accel := lis3dh.New(i2c)
err := accel.Configure(lis3dh.Config{ accel.Address = lis3dh.Address1 // address on the Circuit Playground Express
Address: lis3dh.Address1, // address on the Circuit Playground Express accel.Configure()
}) accel.SetRange(lis3dh.RANGE_2_G)
for err != nil {
println("could not configure LIS3DH:", err)
time.Sleep(time.Second)
}
err = accel.SetRange(lis3dh.RANGE_2_G)
for err != nil {
println("could not set acceleration range:", err)
time.Sleep(time.Second)
}
println(accel.Connected()) println(accel.Connected())
-41
View File
@@ -46,10 +46,6 @@ var DefaultDeviceIdentifier = DeviceIdentifierFunc(func(id JedecID) Attrs {
return GD25Q16C() return GD25Q16C()
case 0xC84017: case 0xC84017:
return GD25Q64C() return GD25Q64C()
case 0x856015:
return P25Q16H()
case 0xEF4014:
return W25Q80DV()
case 0xEF4015: case 0xEF4015:
return W25Q16JVIQ() return W25Q16JVIQ()
case 0xEF4016: case 0xEF4016:
@@ -243,24 +239,6 @@ func GD25Q64C() Attrs {
} }
} }
// Settings for the Puya P25Q16H 2MiB SPI flash.
// Datasheet: https://files.seeedstudio.com/wiki/github_weiruanexample/Flash_P25Q16H-UXH-IR_Datasheet.pdf
func P25Q16H() Attrs {
return Attrs{
TotalSize: 1 << 21, // 2 MiB
StartUp: 5000 * time.Microsecond,
JedecID: JedecID{0x85, 0x60, 0x15},
MaxClockSpeedMHz: 55,
QuadEnableBitMask: 0x02,
HasSectorProtection: true,
SupportsFastRead: true,
SupportsQSPI: true,
SupportsQSPIWrites: true,
WriteStatusSplit: true,
SingleStatusByte: false,
}
}
// Settings for the Winbond W25Q16JV-IQ 2MiB SPI flash. Note that JV-IM has a // Settings for the Winbond W25Q16JV-IQ 2MiB SPI flash. Note that JV-IM has a
// different .memory_type (0x70) Datasheet: // different .memory_type (0x70) Datasheet:
// https://www.winbond.com/resource-files/w25q16jv%20spi%20revf%2005092017.pdf // https://www.winbond.com/resource-files/w25q16jv%20spi%20revf%2005092017.pdf
@@ -402,25 +380,6 @@ func W25Q80DL() Attrs {
TotalSize: 1 << 20, // 1 MiB TotalSize: 1 << 20, // 1 MiB
StartUp: 5000 * time.Microsecond, StartUp: 5000 * time.Microsecond,
JedecID: JedecID{0xEF, 0x60, 0x14}, JedecID: JedecID{0xEF, 0x60, 0x14},
MaxClockSpeedMHz: 80,
QuadEnableBitMask: 0x02,
HasSectorProtection: false,
SupportsFastRead: true,
SupportsQSPI: true,
SupportsQSPIWrites: false,
WriteStatusSplit: false,
SingleStatusByte: false,
}
}
// Settings for the Winbond W25Q80DV 2MiB SPI flash.
// Datasheet:
// https://www.winbond.com/resource-files/w25q80dv%20dl_revh_10022015.pdf
func W25Q80DV() Attrs {
return Attrs{
TotalSize: 1 << 21, // 2 MiB
StartUp: 5000 * time.Microsecond,
JedecID: JedecID{0xEF, 0x40, 0x14},
MaxClockSpeedMHz: 104, MaxClockSpeedMHz: 104,
QuadEnableBitMask: 0x02, QuadEnableBitMask: 0x02,
HasSectorProtection: false, HasSectorProtection: false,
+13 -9
View File
@@ -5,28 +5,29 @@
package ft6336 package ft6336
import ( import (
"machine"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/legacy" "tinygo.org/x/drivers/internal/legacy"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/touch" "tinygo.org/x/drivers/touch"
) )
// Device wraps FT6336 I2C Self-Capacitive touch // Device wraps FT6336 I2C Self-Capacitive touch
type Device struct { type Device struct {
bus drivers.I2C bus drivers.I2C
buf []byte buf []byte
Address uint8 Address uint8
intPin machine.Pin configurePins func()
} }
// New returns FT6336 device for the provided I2C bus using default address. // New returns FT6336 device for the provided I2C bus using default address.
func New(i2c drivers.I2C, intPin machine.Pin) *Device { func New(i2c drivers.I2C, intPin pin.Input) *Device {
return &Device{ return &Device{
bus: i2c, bus: i2c,
buf: make([]byte, 11), buf: make([]byte, 11),
Address: Address, Address: Address,
intPin: intPin, configurePins: func() {
pin.ConfigureInputPulldown(intPin)
},
} }
} }
@@ -36,8 +37,11 @@ type Config struct {
// Configure the FT6336 device. // Configure the FT6336 device.
func (d *Device) Configure(config Config) error { func (d *Device) Configure(config Config) error {
if d.configurePins == nil {
return pin.ErrConfigBeforeInstantiated
}
d.write1Byte(0xA4, 0x00) d.write1Byte(0xA4, 0x00)
d.intPin.Configure(machine.PinConfig{Mode: machine.PinInputPulldown}) d.configurePins()
return nil return nil
} }
+15 -15
View File
@@ -5,12 +5,12 @@ package gc9a01 // import "tinygo.org/x/drivers/gc9a01"
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"errors" "errors"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
// Rotation controls the rotation used by the display. // Rotation controls the rotation used by the display.
@@ -22,10 +22,10 @@ type FrameRate uint8
// Device wraps an SPI connection. // Device wraps an SPI connection.
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
resetPin machine.Pin resetPin pin.OutputFunc
csPin machine.Pin csPin pin.OutputFunc
blPin machine.Pin blPin pin.OutputFunc
width int16 width int16
height int16 height int16
columnOffsetCfg int16 columnOffsetCfg int16
@@ -52,17 +52,17 @@ type Config struct {
} }
// New creates a new ST7789 connection. The SPI wire must already be configured. // 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 drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) Device {
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(resetPin)
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(blPin)
return Device{ return Device{
bus: bus, bus: bus,
resetPin: resetPin, resetPin: resetPin.Set,
dcPin: dcPin, dcPin: dcPin.Set,
csPin: csPin, csPin: csPin.Set,
blPin: blPin, blPin: blPin.Set,
} }
} }
@@ -226,7 +226,7 @@ func (d *Device) Data(data uint8) {
// Tx sends data to the display // Tx sends data to the display
func (d *Device) Tx(data []byte, isCommand bool) { func (d *Device) Tx(data []byte, isCommand bool) {
d.dcPin.Set(!isCommand) d.dcPin(!isCommand)
d.bus.Tx(data, nil) d.bus.Tx(data, nil)
} }
+18 -10
View File
@@ -5,30 +5,38 @@
package hcsr04 package hcsr04
import ( import (
"machine"
"time" "time"
"tinygo.org/x/drivers/internal/pin"
) )
const TIMEOUT = 23324 // max sensing distance (4m) const TIMEOUT = 23324 // max sensing distance (4m)
// Device holds the pins // Device holds the pins
type Device struct { type Device struct {
trigger machine.Pin trigger pin.OutputFunc
echo machine.Pin echo pin.InputFunc
configurePins func()
} }
// New returns a new ultrasonic driver given 2 pins // New returns a new ultrasonic driver given 2 pins
func New(trigger, echo machine.Pin) Device { func New(trigger pin.Output, echo pin.Input) Device {
return Device{ return Device{
trigger: trigger, trigger: trigger.Set,
echo: echo, echo: echo.Get,
configurePins: func() {
pin.ConfigureOutput(trigger)
pin.ConfigureInput(echo)
},
} }
} }
// Configure configures the pins of the Device // Configure configures the pins of the Device
func (d *Device) Configure() { func (d *Device) Configure() {
d.trigger.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.configurePins == nil {
d.echo.Configure(machine.PinConfig{Mode: machine.PinInput}) panic(pin.ErrConfigBeforeInstantiated)
}
d.configurePins()
} }
// ReadDistance returns the distance of the object in mm // ReadDistance returns the distance of the object in mm
@@ -52,7 +60,7 @@ func (d *Device) ReadPulse() int32 {
d.trigger.Low() d.trigger.Low()
i := uint8(0) i := uint8(0)
for { for {
if d.echo.Get() { if d.echo() {
t = time.Now() t = time.Now()
break break
} }
@@ -66,7 +74,7 @@ func (d *Device) ReadPulse() int32 {
} }
i = 0 i = 0
for { for {
if !d.echo.Get() { if !d.echo() {
return int32(time.Since(t).Microseconds()) return int32(time.Since(t).Microseconds())
} }
i++ i++
+5 -5
View File
@@ -210,7 +210,7 @@ func (d *Device) SendCommand(command byte) {
d.bus.SetCommandMode(true) d.bus.SetCommandMode(true)
d.bus.Write([]byte{command}) d.bus.Write([]byte{command})
for d.busy(command == DISPLAY_CLEAR || command == CURSOR_HOME) { for d.isBusy(command == DISPLAY_CLEAR || command == CURSOR_HOME) {
} }
} }
@@ -219,7 +219,7 @@ func (d *Device) sendData(data byte) {
d.bus.SetCommandMode(false) d.bus.SetCommandMode(false)
d.bus.Write([]byte{data}) d.bus.Write([]byte{data})
for d.busy(false) { for d.isBusy(false) {
} }
} }
@@ -231,9 +231,9 @@ func (d *Device) CreateCharacter(cgramAddr uint8, data []byte) {
} }
} }
// busy returns true when hd447890 is busy // isBusy returns true when hd447890 is isBusy
// or after the timeout specified // or after the timeout specified
func (d *Device) busy(longDelay bool) bool { func (d *Device) isBusy(longDelay bool) bool {
if d.bus.WriteOnly() { if d.bus.WriteOnly() {
// Can't read busy flag if write only, so sleep a bit then return // Can't read busy flag if write only, so sleep a bit then return
if longDelay { if longDelay {
@@ -261,7 +261,7 @@ func (d *Device) busy(longDelay bool) bool {
// Busy returns true when hd447890 is busy // Busy returns true when hd447890 is busy
func (d *Device) Busy() bool { func (d *Device) Busy() bool {
return d.busy(false) return d.isBusy(false)
} }
// Size returns the current size of the display. // Size returns the current size of the display.
-191
View File
@@ -1,191 +0,0 @@
package honeyhsc
import (
"errors"
"math"
"tinygo.org/x/drivers"
)
var (
errSensorMissing = errors.New("hsc: not connected")
errDiagnostic = errors.New("hsc: diagnostic error")
)
const (
measuremask = drivers.Pressure | drivers.Temperature
statusMask = 0b1100_0000
statusOffset = 6
)
// DevI2C is the TruStability® High Accuracy Silicon Ceramic (HSC) Series is a piezoresistive silicon pressure sensor offering a ratiometric
// analog or digital output for reading pressure over the specified full scale pressure span and temperature range.
type DevI2C struct {
bus drivers.I2C
dev
addr uint8
buf [6]byte
}
// NewDevI2C creates and returns a new DevI2C that communicates with an HSC device over the provided I2C bus.
// Parameters:
// - bus: the I2C bus to use.
// - addr: the 7-bit I2C address of the sensor.
// - outMin, outMax: raw output code range (counts) corresponding to the pressure span. Depends on sensor model.
// - pMin, pMax: pressure range endpoints in millipascals (mPa). Depends on sensor model.
//
// The returned DevI2C will use these calibration parameters to convert raw bridge counts to pressure.
func NewDevI2C(bus drivers.I2C, addr, outMin, outMax uint16, pMin, pMax int32) *DevI2C {
h := &DevI2C{
bus: bus,
addr: uint8(addr),
dev: dev{
cmin: outMin,
cmax: outMax,
pmin: pMin,
pmax: pMax,
},
}
return h
}
// ReadTemperature reads and returns the temperature in milliKelvin (mC) from the I2C-attached HSC device.
// It performs an Update internally to get the latest temperature value.
func (h *DevI2C) ReadTemperature() (int32, error) {
err := h.Update(drivers.Temperature)
if err != nil {
return 0, err
}
return h.Temperature(), nil
}
// Update reads both temperature and pressure data from the I2C-attached HSC device when
// the requested measurement mask includes pressure or temperature.
// If neither pressure nor temperature is requested, Update is a no-op.
func (d *DevI2C) Update(which drivers.Measurement) error {
// Update performs an I2C transaction to read 4 bytes, parses the status bits, 14-bit bridge data and
// temperature bits, and forwards them to the internal update routine. Any I2C transport error is returned,
// as well as errors produced by the internal update (e.g. errSensorMissing, errDiagnostic).
if which&measuremask == 0 {
return nil
}
rbuf := d.buf[:4]
wbuf := d.buf[4:6]
const reg = 0
value := (d.addr << 1) | 1
wbuf[0] = reg
wbuf[1] = value
err := d.bus.Tx(uint16(d.addr), wbuf, rbuf)
if err != nil {
return err
}
status := (rbuf[0] & statusMask) >> statusOffset
bridgeData := (uint16(rbuf[0]&^statusMask) << 8) | uint16(rbuf[1])
tempData := uint16(rbuf[2])<<8 | uint16(rbuf[3]&0xe0)>>5
return d.dev.update(status, bridgeData, tempData)
}
type pinout func(level bool)
// DevI2C is the TruStability® High Accuracy Silicon Ceramic (HSC) Series is a piezoresistive silicon pressure sensor offering a ratiometric
// analog or digital output for reading pressure over the specified full scale pressure span and temperature range.
type DevSPI struct {
spi drivers.SPI
cs pinout
dev
buf [4]byte
}
// NewDevSPI creates and returns a new DevSPI that communicates with an HSC device over SPI.
// Parameters:
// - conn: the SPI connection to use.
// - cs: a chip-select function that drives the device select line low/high.
// - outMin, outMax: raw output code range (counts) corresponding to the pressure span. Depends on sensor model.
// - pMin, pMax: pressure range endpoints in millipascals (mPa). Depends on sensor model.
//
// The function returns the constructed DevSPI and an error value (currently always nil).
func NewDevSPI(conn drivers.SPI, cs pinout, outMin, outMax uint16, pMin, pMax int32) (*DevSPI, error) {
h := &DevSPI{
spi: conn,
cs: cs,
dev: dev{
cmin: outMin,
cmax: outMax,
pmin: pMin,
pmax: pMax,
},
}
return h, nil
}
// ReadTemperature reads and returns the temperature in milliKelvin (mC) from the SPI-attached HSC device.
// It performs an Update internally to get the latest temperature value.
func (h *DevSPI) ReadTemperature() (int32, error) {
err := h.Update(drivers.Temperature)
if err != nil {
return 0, err
}
return h.Temperature(), nil
}
// Update reads pressure and temperature data from the SPI-attached HSC device when the requested measurement mask includes
// pressure or temperature. If neither pressure nor temperature is requested, Update is a no-op.
func (h *DevSPI) Update(which drivers.Measurement) error {
// It toggles the provided chip-select, performs an SPI transfer to read 4 bytes, parses the status bits,
// 14-bit bridge data and temperature bits, and forwards them to the internal update routine. Any SPI
// transport error is returned, as well as errors produced by the internal update (e.g. errSensorMissing, errDiagnostic).
if which&measuremask == 0 {
return nil
}
buf := &h.buf
h.cs(false)
err := h.spi.Tx(nil, buf[:4])
h.cs(true)
if err != nil {
return err
}
// First two bits are status bits.
status := (buf[0] & statusMask) >> statusOffset
bridgeData := (uint16(buf[0]&^statusMask) << 8) | uint16(buf[1])
tempData := uint16(buf[2])<<8 | uint16(buf[3]&0xe0)>>5
return h.dev.update(status, bridgeData, tempData)
}
type dev struct {
pressure int32
temp int32
cmin, cmax uint16
pmin, pmax int32
}
// Pressure returns the most recently computed pressure value in millipascals (mPa).
// The value is taken from the last successful Update.
func (d *dev) Pressure() int32 {
return d.pressure
}
// Temperature returns the most recently read temperature value in milliKelvin (mC).
// The value is taken from the last successful Update.
func (d *dev) Temperature() int32 {
return d.temp + 273_150
}
// update interprets raw sensor fields (status, bridgeData, tempData) and updates the dev's stored
// pressure and temperature. It returns errSensorMissing when the temperature raw value indicates no sensor
// (tempData == math.MaxUint16), errDiagnostic when the status indicates a device diagnostic condition
// (status == 3), or nil on success. Pressure is computed with integer arithmetic using the configured
// cmin/cmax -> pmin/pmax linear mapping in order to avoid overflows.
func (d *dev) update(status uint8, bridgeData, tempData uint16) error {
if tempData == math.MaxUint16 {
return errSensorMissing
} else if status == 3 {
return errDiagnostic
}
// Take care not to overflow here.
p := (int32(bridgeData)-int32(d.cmin))*(d.pmax-d.pmin)/int32(d.cmax-d.cmin) + d.pmin
d.temp = int32(tempData)
d.pressure = p
return nil
}
-2
View File
@@ -2,8 +2,6 @@
package hts221 package hts221
import "tinygo.org/x/drivers"
// Configure sets up the HTS221 device for communication. // Configure sets up the HTS221 device for communication.
func (d *Device) Configure() { func (d *Device) Configure() {
// read calibration data // read calibration data
-62
View File
@@ -1,62 +0,0 @@
package legacy
import (
"errors"
"tinygo.org/x/drivers/internal/pin"
)
// The pingconfig group of files serve to abstract away
// pin configuration calls on the machine.Pin type.
// It was observed this way of developing drivers was
// non-portable and unusable on "big" Go projects so
// future projects should NOT configure pins in driver code.
// Users must configure pins before passing them as arguments
// to drivers.
// ConfigurePinOut is a legacy function used to configure pins as outputs.
//
// Deprecated: Do not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigurePinOut(po pin.Output) {
configurePinOut(po)
}
// ConfigurePinInput is a legacy function used to configure pins as inputs.
//
// Deprecated: Do not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigurePinInputPulldown(pi pin.Input) {
configurePinInputPulldown(pi)
}
// ConfigurePinInput is a legacy function used to configure pins as inputs.
//
// Deprecated: Do not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigurePinInput(pi pin.Input) {
configurePinInput(pi)
}
// ConfigurePinInput is a legacy function used to configure pins as inputs.
//
// Deprecated: Do not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigurePinInputPullup(pi pin.Input) {
configurePinInputPullup(pi)
}
// PinIsNoPin returns true if the argument is a machine.Pin type and is the machine.NoPin predeclared type.
//
// Deprecated: Drivers do not require pin knowledge from now on.
func PinIsNoPin(pin any) bool {
return pinIsNoPin(pin)
}
var (
ErrConfigBeforeInstantiated = errors.New("device must be instantiated with New before calling Configure method")
)
-15
View File
@@ -1,15 +0,0 @@
//go:build !tinygo
package legacy
import "tinygo.org/x/drivers/internal/pin"
// This file compiles for non-tinygo builds
// for use with "big" or "upstream" Go where
// there is no machine package.
func configurePinOut(p pin.Output) {}
func configurePinInput(p pin.Input) {}
func configurePinInputPulldown(p pin.Input) {}
func configurePinInputPullup(p pin.Input) {}
func pinIsNoPin(a any) bool { return false }
-37
View File
@@ -1,37 +0,0 @@
//go:build baremetal
package legacy
import (
"machine"
"tinygo.org/x/drivers/internal/pin"
)
func configurePinOut(po pin.Output) {
configurePin(po, machine.PinOutput)
}
func configurePinInputPulldown(pi pin.Input) {
configurePin(pi, pulldown) // some chips do not have pull down, in which case pulldown==machine.PinInput.
}
func configurePinInput(pi pin.Input) {
configurePin(pi, machine.PinInput)
}
func configurePinInputPullup(pi pin.Input) {
configurePin(pi, pullup) // some chips do not have pull up, in which case pullup==machine.PinInput.
}
func pinIsNoPin(a any) bool {
p, ok := a.(machine.Pin)
return ok && p == machine.NoPin
}
func configurePin(p any, mode machine.PinMode) {
machinePin, ok := p.(machine.Pin)
if ok {
machinePin.Configure(machine.PinConfig{Mode: mode})
}
}
-72
View File
@@ -1,72 +0,0 @@
// package pin implements a TinyGo Pin HAL.
// It serves to eliminate machine.Pin from driver constructors
// so that drivers can be used in "big" Go projects where
// there is no machine package.
// This file contains both function and interface-style Pin HAL definitions.
package pin
// OutputFunc is hardware abstraction for a pin which outputs a
// digital signal (high or low level).
//
// // Code conversion demo: from machine.Pin to pin.OutputFunc
// led := machine.LED
// led.Configure(machine.PinConfig{Mode: machine.Output})
// var pin pin.OutputFunc = led.Set // Going from a machine.Pin to a pin.OutputFunc
//
// This is an alternative to [Output] which is an interface type.
type OutputFunc func(level bool)
// High sets the underlying pin's level to high. This is equivalent to calling PinOutput(true).
func (setPin OutputFunc) High() {
setPin(true)
}
// Low sets the underlying pin's level to low. This is equivalent to calling PinOutput(false).
func (setPin OutputFunc) Low() {
setPin(false)
}
// InputFunc is hardware abstraction for a pin which receives a
// digital signal and reads it (high or low level).
//
// // Code conversion demo: from machine.Pin to pin.InputFunc
// input := machine.LED
// input.Configure(machine.PinConfig{Mode: machine.PinInputPulldown}) // or use machine.PinInputPullup or machine.Input
// var pin pin.InputFunc = input.Get // Going from a machine.Pin to a pin.InputFunc
//
// This is an alternative to [Input] which is an interface type.
type InputFunc func() (level bool)
// // Below is an example on how to define a input/output pin HAL for a
// // pin that must switch between input and output mode:
//
// var pinIsOutput bool
// var po PinOutputFunc = func(b bool) {
// if !pinIsOutput {
// pin.Configure(outputMode)
// pinIsOutput = true
// }
// pin.Set(b)
// }
//
// var pi PinInputFunc = func() bool {
// if pinIsOutput {
// pin.Configure(inputMode)
// pinIsOutput = false
// }
// return pin.Get()
// }
// Output interface represents a pin hardware abstraction layer for a pin that can output a digital signal.
//
// This is an alternative to [OutputFunc] abstraction which is a function type.
type Output interface {
Set(level bool)
}
// Input interface represents a pin hardware abstraction layer for a pin that can read a digital signal.
//
// This is an alternative to [InputFunc] abstraction which is a function type.
type Input interface {
Get() (level bool)
}
+98
View File
@@ -0,0 +1,98 @@
package pin
import "errors"
// OutputFunc is hardware abstraction for a pin which outputs a
// digital signal (high or low level).
//
// // Code conversion demo: from machine.Pin to pin.OutputFunc
// led := machine.LED
// led.Configure(machine.PinConfig{Mode: machine.PinOutput})
// var p pin.OutputFuncFunc = led.Set // Going from a machine.Pin to a pin.OutputFunc
type OutputFunc func(level bool)
func (o OutputFunc) High() {
o(true)
}
func (o OutputFunc) Low() {
o(false)
}
// InputFunc is hardware abstraction for a pin which receives a
// digital signal and reads it (high or low level).
//
// // Code conversion demo: from machine.Pin to pin.InputFunc
// input := machine.LED
// input.Configure(machine.PinConfig{Mode: machine.PinInputPulldown}) // or use machine.PinInputPullup or machine.PinInput
// var p pin.InputFunc = input.Get // Going from a machine.Pin to a drivers.PinInput
type InputFunc func() (level bool)
// PinOutput represents a pin hardware abstraction layer for a pin that can output a digital signal.
// This is an wrapper to pin.OutputFunc abstraction which is a function type.
//
// func New(p1, p2, p3 pin.Output) *Device {
// return NewWithPinfuncs(p1.Set, p2.Set, p3.Set)
// }
//
// func NewWithPinfuncs(p1, p2, p3 pin.OutputFunc) *Device {
// return &Device{p1:p1, p2:p2, p3:p3}
// }
//
// [relevant issue]: https://github.com/tinygo-org/drivers/pull/749/files
type Output interface {
Set(level bool)
}
// PinInput represents a pin hardware abstraction layer. See [PinOutput] for
// more information on why this is "legacy".
type Input interface {
Get() (level bool)
}
// ConfigureOutput is a legacy function used to configure pins as outputs.
//
// Deprecated: You should not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigureOutput(po Output) {
configureOutput(po)
}
// ConfigureInput is a legacy function used to configure pins as inputs.
//
// Deprecated: You should not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigureInputPulldown(pi Input) {
configureInputPulldown(pi)
}
// ConfigureInput is a legacy function used to configure pins as inputs.
//
// Deprecated: You should not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigureInput(pi Input) {
configureInput(pi)
}
// ConfigureInputPullup is a legacy function used to configure pins as inputs.
//
// Deprecated: You should not configure pins in drivers.
// This is a legacy feature and should only be used by drivers that
// previously configured pins in initialization to avoid breaking users.
func ConfigureInputPullup(pi Input) {
configureInputPullup(pi)
}
// IsNotPin returns true if the argument is a machine.Pin type and is the machine.NoPin predeclared type.
//
// Deprecated: Drivers should not require pin knowledge.
func IsNotPin(pin any) bool {
return isNotPin(pin)
}
var (
ErrConfigBeforeInstantiated = errors.New("device must be instantiated with New before calling Configure method")
)
+9
View File
@@ -0,0 +1,9 @@
//go:build !baremetal
package pin
func configureOutput(p Output) {}
func configureInput(p Input) {}
func configureInputPulldown(p Input) {}
func configureInputPullup(p Input) {}
func isNotPin(a any) bool { return false }
@@ -1,6 +1,6 @@
//go:build baremetal && fe310 //go:build baremetal && fe310
package legacy package pin
import "machine" import "machine"
@@ -1,6 +1,6 @@
//go:build baremetal && !fe310 //go:build baremetal && !fe310
package legacy package pin
import "machine" import "machine"
+33
View File
@@ -0,0 +1,33 @@
//go:build baremetal
package pin
import "machine"
func configureOutput(p Output) {
configure(p, machine.PinOutput)
}
func configureInputPulldown(p Input) {
configure(p, pulldown) // some chips do not have pull down, in which case pulldown==machine.PinInput.
}
func configureInput(p Input) {
configure(p, machine.PinInput)
}
func configureInputPullup(p Input) {
configure(p, pullup) // some chips do not have pull up, in which case pullup==machine.PinInput.
}
func isNotPin(a any) bool {
p, ok := a.(machine.Pin)
return ok && p == machine.NoPin
}
func configure(p any, mode machine.PinMode) {
machinePin, ok := p.(machine.Pin)
if ok {
machinePin.Configure(machine.PinConfig{Mode: mode})
}
}
-143
View File
@@ -1,143 +0,0 @@
package regmap
import (
"encoding/binary"
"io"
"tinygo.org/x/drivers"
)
// Device8 implements common logic to most 8-bit peripherals with an I2C or SPI bus.
// All methods expect the target to support conventional register read and write operations
// where the first byte sent is the register address being accessed.
//
// All methods use an internal buffer and perform no dynamic memory allocation.
type Device8 struct {
buf [10]byte
}
// clear zeroes Device8's buffers.
func (d *Device8) clear() {
d.buf = [10]byte{}
}
// I2C methods.
// Read8I2C reads a single byte from register addr of the device at i2cAddr using the provided I2C bus.
func (d *Device8) Read8I2C(bus drivers.I2C, i2cAddr uint16, addr uint8) (byte, error) {
d.buf[0] = addr
err := bus.Tx(i2cAddr, d.buf[0:1], d.buf[1:2])
return d.buf[1], err
}
// Read16I2C reads a 16-bit value from register addr of the device at i2cAddr using the provided I2C bus.
// The byte order is specified by order.
func (d *Device8) Read16I2C(bus drivers.I2C, i2cAddr uint16, addr uint8, order binary.ByteOrder) (uint16, error) {
d.buf[0] = addr
err := bus.Tx(i2cAddr, d.buf[0:1], d.buf[1:3])
return order.Uint16(d.buf[1:3]), err
}
// Read32I2C reads a 32-bit value from register addr of the device at i2cAddr using the provided I2C bus.
// The byte order is specified by order.
func (d *Device8) Read32I2C(bus drivers.I2C, i2cAddr uint16, addr uint8, order binary.ByteOrder) (uint32, error) {
d.buf[0] = addr
err := bus.Tx(i2cAddr, d.buf[0:1], d.buf[1:5])
return order.Uint32(d.buf[1:5]), err
}
// ReadDataI2C reads dataLength bytes from register addr of the device at i2cAddr using the provided I2C bus.
// The data is stored in dataDestination.
func (d *Device8) ReadDataI2C(bus drivers.I2C, i2cAddr uint16, addr uint8, dataDestination []byte) error {
d.buf[0] = addr
return bus.Tx(i2cAddr, d.buf[:1], dataDestination)
}
// Write8I2C writes a single byte value to register addr of the device at i2cAddr using the provided I2C bus.
func (d *Device8) Write8I2C(bus drivers.I2C, i2cAddr uint16, addr, value uint8) error {
d.buf[0] = addr
d.buf[1] = value
return bus.Tx(i2cAddr, d.buf[:2], nil)
}
// Write16I2C writes a 16-bit value to register addr of the device at i2cAddr using the provided I2C bus.
// The byte order is specified by order.
func (d *Device8) Write16I2C(bus drivers.I2C, i2cAddr uint16, addr uint8, value uint16, order binary.ByteOrder) error {
d.buf[0] = addr
order.PutUint16(d.buf[1:3], value)
return bus.Tx(i2cAddr, d.buf[0:3], nil)
}
// Write32I2C writes a 32-bit value to register addr of the device at i2cAddr using the provided I2C bus.
// The byte order is specified by order.
func (d *Device8) Write32I2C(bus drivers.I2C, i2cAddr uint16, addr uint8, value uint32, order binary.ByteOrder) error {
d.buf[0] = addr
order.PutUint32(d.buf[1:5], value)
return bus.Tx(i2cAddr, d.buf[0:5], nil)
}
// SPI methods.
// Read8SPI reads a single byte from register addr using the provided SPI bus.
func (d *Device8) Read8SPI(bus drivers.SPI, addr uint8) (byte, error) {
d.clear()
d.buf[0] = addr
err := bus.Tx(d.buf[0:1], d.buf[1:2]) // We suppose data is returned after first byte in SPI.
return d.buf[1], err
}
// Read16SPI reads a 16-bit value from register addr using the provided SPI bus. The byte order is specified by order.
func (d *Device8) Read16SPI(bus drivers.SPI, addr uint8, order binary.ByteOrder) (uint16, error) {
d.clear()
d.buf[0] = addr
err := bus.Tx(d.buf[0:3], d.buf[3:6]) // We suppose data is returned after first byte in SPI.
return order.Uint16(d.buf[4:6]), err
}
// Read32SPI reads a 32-bit value from register addr using the provided SPI bus. The byte order is specified by order.
func (d *Device8) Read32SPI(bus drivers.SPI, addr uint8, order binary.ByteOrder) (uint32, error) {
d.clear()
d.buf[0] = addr
err := bus.Tx(d.buf[0:5], d.buf[5:10]) // We suppose data is returned after first byte in SPI.
return order.Uint32(d.buf[6:10]), err
}
// ReadDataSPI reads data from a 8bit device address. It assumes data at register address is sent back
// from device after first byte is written as address.
// It needs the auxiliary buffer length to be large enough to contain both the write and read portions of buffer,
// so 2*(dataLength+1) < len(auxiliaryBuf) must hold.
func (d *Device8) ReadDataSPI(bus drivers.SPI, addr uint8, dataLength int, auxiliaryBuf []byte) ([]byte, error) {
split := len(auxiliaryBuf) / 2
if split < dataLength+1 {
return nil, io.ErrShortBuffer
}
wbuf, rbuf := auxiliaryBuf[:split], auxiliaryBuf[split:]
wbuf[0] = addr
err := bus.Tx(wbuf, rbuf)
return rbuf[1:], err
}
// Write8SPI writes a single byte value to register addr using the provided SPI bus.
func (d *Device8) Write8SPI(bus drivers.SPI, addr, value uint8) error {
d.clear()
d.buf[0] = addr
d.buf[1] = value
return bus.Tx(d.buf[:2], nil)
}
// Write16SPI writes a 16-bit value to register addr using the provided SPI bus. The byte order is specified by order.
func (d *Device8) Write16SPI(bus drivers.SPI, addr uint8, value uint16, order binary.ByteOrder) error {
d.clear()
d.buf[0] = addr
order.PutUint16(d.buf[1:3], value)
return bus.Tx(d.buf[:3], nil)
}
// Write32SPI writes a 32-bit value to register addr using the provided SPI bus. The byte order is specified by order.
func (d *Device8) Write32SPI(bus drivers.SPI, addr uint8, value uint32, order binary.ByteOrder) error {
d.clear()
d.buf[0] = addr
order.PutUint32(d.buf[1:5], value)
return bus.Tx(d.buf[:5], nil)
}
-196
View File
@@ -1,196 +0,0 @@
// Package regmap provides transaction-based interfaces for reading and writing
// to device registers over I2C and SPI buses with pre-allocated buffers.
package regmap
import (
"errors"
"tinygo.org/x/drivers"
)
var (
// errNotInTx indicates an operation was attempted outside of an active transaction.
errNotInTx = errors.New("device not in Tx")
// errInTx indicates a transaction was started while another is still active.
errInTx = errors.New("device already in Tx")
// errShortWriteBuffer indicates the write buffer is too small for the requested operation.
errShortWriteBuffer = errors.New("device write buffer too short")
// errShortReadBuffer indicates the read buffer is too small for the requested operation.
errShortReadBuffer = errors.New("device read buffer too short")
)
// Device8Txer wraps a Device8 to provide buffered transaction support for
// I2C and SPI operations. It maintains pre-allocated buffers to avoid heap
// allocations during register access operations.
//
// Users must call SetBuffers to configure the write and read buffers before
// initiating transactions.
type Device8Txer struct {
Device8
writeBuf []byte // Pre-allocated buffer for write operations
readBuf []byte // Pre-allocated buffer for read operations
inTx bool // Tracks whether a transaction is currently active
}
// SetTxBuffers configures the write and read buffers for this device.
// These buffers are reused across transactions to avoid heap allocations.
//
// The writebuf should be large enough to hold the register address plus
// all data bytes to be written in a single transaction.
func (d *Device8Txer) SetTxBuffers(writebuf, readbuf []byte) {
d.readBuf = readbuf
d.writeBuf = writebuf
}
// Tx8 represents an active transaction for an 8-bit register device.
// It tracks the write buffer and current offset as data is added to the transaction.
//
// Use AddWriteByte or AddWriteData to add data to the transaction, then call
// DoTxI2C or DoTxSPI to execute the transaction over the bus.
type Tx8 struct {
dw *Device8Txer // Reference to the parent device
off int // Current offset in the write buffer
}
// Tx initiates a new transaction for writing to the specified register address.
//
// Parameters:
// - writeAddr: The 8-bit register address to write to
//
// Returns a Tx8 handle that can be used to add data and execute the transaction.
//
// Returns an error if:
// - A transaction is already active (errInTx)
// - The write buffer is too short (errShortWriteBuffer)
func (dw *Device8Txer) Tx(writeAddr uint8) (Tx8, error) {
if dw.inTx {
return Tx8{}, errInTx
} else if len(dw.writeBuf) < 1 {
return Tx8{}, errShortWriteBuffer
}
dw.writeBuf[0] = writeAddr
return Tx8{dw: dw, off: 1}, nil
}
// AddWriteData appends multiple bytes to the current transaction's write buffer.
//
// Parameters:
// - buf: Variable number of bytes to add to the transaction
//
// Returns an error if:
// - No transaction is active (errNotInTx)
// - The write buffer doesn't have enough space (errShortWriteBuffer)
func (tx *Tx8) AddWriteData(buf ...byte) error {
if !tx.dw.inTx {
return errNotInTx
}
avail := tx.dw.writeBuf[tx.off:]
if len(avail) < len(buf) {
return errShortWriteBuffer
}
n := copy(avail, buf)
tx.off += n
return nil
}
// AddWriteByte appends a single byte to the current transaction's write buffer.
//
// Parameters:
// - b: The byte to add to the transaction
//
// Returns an error if:
// - No transaction is active (errNotInTx)
// - The write buffer doesn't have enough space (errShortWriteBuffer)
func (tx *Tx8) AddWriteByte(b byte) error {
if !tx.dw.inTx {
return errNotInTx
}
avail := tx.dw.writeBuf[tx.off:]
if len(avail) < 1 {
return errShortWriteBuffer
}
avail[0] = b
tx.off++
return nil
}
// DoTxI2C executes the transaction over an I2C bus.
//
// This performs a combined write-read I2C transaction, first sending the
// register address and any data added to the transaction, then reading
// the specified number of bytes from the device.
//
// Parameters:
// - bus: The I2C bus to communicate over
// - deviceAddr: The I2C address of the target device
// - readLength: Number of bytes to read from the device
//
// Returns the read data as a slice of the internal read buffer, valid until
// the next transaction. The transaction is automatically freed after execution.
//
// Returns an error if:
// - No transaction is active (errNotInTx)
// - The read buffer is too short (errShortReadBuffer)
// - The I2C transaction fails
func (tx *Tx8) DoTxI2C(bus drivers.I2C, deviceAddr uint16, readLength int) ([]byte, error) {
if tx.off == 0 || !tx.dw.inTx {
return nil, errNotInTx
}
defer tx.freeTx()
if len(tx.dw.readBuf) < readLength {
return nil, errShortReadBuffer
}
rbuf := tx.dw.readBuf[:readLength]
err := bus.Tx(deviceAddr, tx.dw.writeBuf[:tx.off], rbuf)
if err != nil {
return nil, err
}
return rbuf, err
}
// DoTxSPI executes the transaction over an SPI bus.
//
// This performs a full-duplex SPI transaction, simultaneously writing the
// register address and data while reading the same number of bytes from the device.
//
// If no read buffer was configured (readBuf is nil), this performs a write-only
// transaction and returns nil without error.
//
// Parameters:
// - bus: The SPI bus to communicate over
//
// Returns the read data as a slice of the internal read buffer (same length as
// the write data), valid until the next transaction. The transaction is
// automatically freed after execution.
//
// Returns an error if:
// - No transaction is active (errNotInTx)
// - The read buffer is too short (errShortReadBuffer)
// - The SPI transaction fails
func (tx *Tx8) DoTxSPI(bus drivers.SPI) (readBuf []byte, err error) {
if tx.off == 0 || !tx.dw.inTx {
return nil, errNotInTx
}
defer tx.freeTx()
if tx.dw.readBuf == nil {
err = bus.Tx(tx.dw.writeBuf[:tx.off], nil) // Special case, only use write buffer functionality.
return nil, err
} else if len(readBuf) < tx.off {
return nil, errShortReadBuffer
}
rbuf := tx.dw.readBuf[:tx.off]
err = bus.Tx(tx.dw.writeBuf[:tx.off], rbuf)
if err != nil {
return nil, err
}
return rbuf, err
}
// freeTx marks the transaction as complete, allowing a new transaction to be started.
// This is called internally by DoTxI2C and DoTxSPI after the transaction completes.
func (tx *Tx8) freeTx() {
tx.dw.inTx = false
}
-123
View File
@@ -1,123 +0,0 @@
package regmap
import (
"encoding/binary"
"tinygo.org/x/drivers"
)
// Device8SPI implements common logic to most 8-bit peripherals with an SPI bus.
// All methods expect the target to support conventional register read and write operations
// where the first byte sent is the register address being accessed.
//
// All methods use an internal buffer and perform no dynamic memory allocation.
type Device8SPI struct {
bus drivers.SPI
order binary.ByteOrder
d Device8
}
// SetBus sets the SPI bus and byte order for the Device8SPI.
//
// As a hint, most SPI devices use big-endian (MSB) byte order.
// - Big endian: A value of 0x1234 is transmitted as 0x12 followed by 0x34.
// - Little endian: A value of 0x1234 is transmitted as 0x34 followed by 0x12.
func (d *Device8SPI) SetBus(bus drivers.SPI, order binary.ByteOrder) {
d.bus = bus
d.order = order
}
// Read8 reads a single byte from register addr.
func (d *Device8SPI) Read8(addr uint8) (byte, error) {
return d.d.Read8SPI(d.bus, addr)
}
// Read16 reads a 16-bit value from register addr.
func (d *Device8SPI) Read16(addr uint8) (uint16, error) {
return d.d.Read16SPI(d.bus, addr, d.order)
}
// Read32 reads a 32-bit value from register addr.
func (d *Device8SPI) Read32(addr uint8) (uint32, error) {
return d.d.Read32SPI(d.bus, addr, d.order)
}
// ReadData reads dataLength bytes from register addr. Due to the internal functioning of
// SPI, an auxiliary buffer must be provided to perform the operation and avoid memory allocation.
// The returned slice is a subslice of auxBuffer containing the read data.
func (d *Device8SPI) ReadData(addr uint8, datalength int, auxBuffer []byte) ([]byte, error) {
return d.d.ReadDataSPI(d.bus, addr, datalength, auxBuffer)
}
// Write8 writes a single byte value to register addr.
func (d *Device8SPI) Write8(addr, value uint8) error {
return d.d.Write8SPI(d.bus, addr, value)
}
// Write16 writes a 16-bit value to register addr.
func (d *Device8SPI) Write16(addr uint8, value uint16) error {
return d.d.Write16SPI(d.bus, addr, value, d.order)
}
// Write32 writes a 32-bit value to register addr.
func (d *Device8SPI) Write32(addr uint8, value uint32) error {
return d.d.Write32SPI(d.bus, addr, value, d.order)
}
// Device8I2C implements common logic to most 8-bit peripherals with an I2C bus.
// All methods expect the target to support conventional register read and write operations
// where the first byte sent is the register address being accessed.
//
// All methods use an internal buffer and perform no dynamic memory allocation.
type Device8I2C struct {
bus drivers.I2C
i2cAddr uint16
order binary.ByteOrder
d Device8
}
// SetBus sets the I2C bus, device address, and byte order for the Device8I2C.
//
// As a hint, most I2C devices use big-endian (MSB) byte order.
// - Big endian: A value of 0x1234 is transmitted as 0x12 followed by 0x34.
// - Little endian: A value of 0x1234 is transmitted as 0x34 followed by 0x12.
func (d *Device8I2C) SetBus(bus drivers.I2C, i2cAddr uint16, order binary.ByteOrder) {
d.bus = bus
d.i2cAddr = i2cAddr
d.order = order
}
// Read8 reads a single byte from register addr.
func (d *Device8I2C) Read8(addr uint8) (byte, error) {
return d.d.Read8I2C(d.bus, d.i2cAddr, addr)
}
// Read16 reads a 16-bit value from register addr.
func (d *Device8I2C) Read16(addr uint8) (uint16, error) {
return d.d.Read16I2C(d.bus, d.i2cAddr, addr, d.order)
}
// Read32 reads a 32-bit value from register addr.
func (d *Device8I2C) Read32(addr uint8) (uint32, error) {
return d.d.Read32I2C(d.bus, d.i2cAddr, addr, d.order)
}
// ReadData reads dataLength bytes from register addr.
func (d *Device8I2C) ReadData(addr uint8, dataDestination []byte) error {
return d.d.ReadDataI2C(d.bus, d.i2cAddr, addr, dataDestination)
}
// Write8 writes a single byte value to register addr.
func (d *Device8I2C) Write8(addr, value uint8) error {
return d.d.Write8I2C(d.bus, d.i2cAddr, addr, value)
}
// Write16 writes a 16-bit value to register addr.
func (d *Device8I2C) Write16(addr uint8, value uint16) error {
return d.d.Write16I2C(d.bus, d.i2cAddr, addr, value, d.order)
}
// Write32 writes a 32-bit value to register addr.
func (d *Device8I2C) Write32(addr uint8, value uint32) error {
return d.d.Write32I2C(d.bus, d.i2cAddr, addr, value, d.order)
}
-34
View File
@@ -1,34 +0,0 @@
package regmap
import (
"fmt"
"tinygo.org/x/drivers"
)
func ExampleDevice8Txer() {
// Initialization.
var dtx Device8Txer
dtx.SetTxBuffers(make([]byte, 256), make([]byte, 256))
// Usage.
const (
defaultAddr = 65
REG_WRITE = 0x1f
IOCTL_CALL = 0xc0
)
tx, err := dtx.Tx(REG_WRITE)
if err != nil {
panic(err)
}
err = tx.AddWriteData(IOCTL_CALL, 0x80, 0x80)
if err != nil {
panic(err)
}
var bus drivers.I2C
readData, err := tx.DoTxI2C(bus, defaultAddr, 20)
if err != nil {
panic(err)
}
fmt.Println(readData)
}
+36 -115
View File
@@ -11,57 +11,37 @@ import (
// Device wraps an I2C connection to a LIS3DH device. // Device wraps an I2C connection to a LIS3DH device.
type Device struct { type Device struct {
bus drivers.I2C bus drivers.I2C
address uint16
r Range
accel [6]byte // stored acceleration data (from the Update call)
}
// Driver configuration, used for the Configure call. All fields are optional.
type Config struct {
Address uint16 Address uint16
r Range
} }
// New creates a new LIS3DH connection. The I2C bus must already be configured. // New creates a new LIS3DH connection. The I2C bus must already be configured.
// //
// This function only creates the Device object, it does not touch the device. // This function only creates the Device object, it does not touch the device.
func New(bus drivers.I2C) Device { func New(bus drivers.I2C) Device {
return Device{bus: bus, address: Address0} return Device{bus: bus, Address: Address0}
} }
// Configure sets up the device for communication // Configure sets up the device for communication
func (d *Device) Configure(config Config) error { func (d *Device) Configure() {
if config.Address != 0 {
d.address = config.Address
}
// enable all axes, normal mode // enable all axes, normal mode
err := legacy.WriteRegister(d.bus, uint8(d.address), REG_CTRL1, []byte{0x07}) legacy.WriteRegister(d.bus, uint8(d.Address), REG_CTRL1, []byte{0x07})
if err != nil {
return err
}
// 400Hz rate // 400Hz rate
err = d.SetDataRate(DATARATE_400_HZ) d.SetDataRate(DATARATE_400_HZ)
if err != nil {
return err
}
// High res & BDU enabled // High res & BDU enabled
err = legacy.WriteRegister(d.bus, uint8(d.address), REG_CTRL4, []byte{0x88}) legacy.WriteRegister(d.bus, uint8(d.Address), REG_CTRL4, []byte{0x88})
if err != nil {
return err
}
// get current range // get current range
d.r, err = d.ReadRange() d.r = d.ReadRange()
return err
} }
// Connected returns whether a LIS3DH has been found. // Connected returns whether a LIS3DH has been found.
// It does a "who am I" request and checks the response. // It does a "who am I" request and checks the response.
func (d *Device) Connected() bool { func (d *Device) Connected() bool {
data := []byte{0} data := []byte{0}
err := legacy.ReadRegister(d.bus, uint8(d.address), WHO_AM_I, data) err := legacy.ReadRegister(d.bus, uint8(d.Address), WHO_AM_I, data)
if err != nil { if err != nil {
return false return false
} }
@@ -69,51 +49,46 @@ func (d *Device) Connected() bool {
} }
// SetDataRate sets the speed of data collected by the LIS3DH. // SetDataRate sets the speed of data collected by the LIS3DH.
func (d *Device) SetDataRate(rate DataRate) error { func (d *Device) SetDataRate(rate DataRate) {
ctl1 := []byte{0} ctl1 := []byte{0}
err := legacy.ReadRegister(d.bus, uint8(d.address), REG_CTRL1, ctl1) err := legacy.ReadRegister(d.bus, uint8(d.Address), REG_CTRL1, ctl1)
if err != nil { if err != nil {
return err println(err.Error())
} }
// mask off bits // mask off bits
ctl1[0] &^= 0xf0 ctl1[0] &^= 0xf0
ctl1[0] |= (byte(rate) << 4) ctl1[0] |= (byte(rate) << 4)
return legacy.WriteRegister(d.bus, uint8(d.address), REG_CTRL1, ctl1) legacy.WriteRegister(d.bus, uint8(d.Address), REG_CTRL1, ctl1)
} }
// SetRange sets the G range for LIS3DH. // SetRange sets the G range for LIS3DH.
func (d *Device) SetRange(r Range) error { func (d *Device) SetRange(r Range) {
ctl := []byte{0} ctl := []byte{0}
err := legacy.ReadRegister(d.bus, uint8(d.address), REG_CTRL4, ctl) err := legacy.ReadRegister(d.bus, uint8(d.Address), REG_CTRL4, ctl)
if err != nil { if err != nil {
return err println(err.Error())
} }
// mask off bits // mask off bits
ctl[0] &^= 0x30 ctl[0] &^= 0x30
ctl[0] |= (byte(r) << 4) ctl[0] |= (byte(r) << 4)
err = legacy.WriteRegister(d.bus, uint8(d.address), REG_CTRL4, ctl) legacy.WriteRegister(d.bus, uint8(d.Address), REG_CTRL4, ctl)
if err != nil {
return err
}
// store the new range // store the new range
d.r = r d.r = r
return nil
} }
// ReadRange returns the current G range for LIS3DH. // ReadRange returns the current G range for LIS3DH.
func (d *Device) ReadRange() (r Range, err error) { func (d *Device) ReadRange() (r Range) {
ctl := []byte{0} ctl := []byte{0}
err = legacy.ReadRegister(d.bus, uint8(d.address), REG_CTRL4, ctl) err := legacy.ReadRegister(d.bus, uint8(d.Address), REG_CTRL4, ctl)
if err != nil { if err != nil {
return 0, err println(err.Error())
} }
// mask off bits // mask off bits
r = Range(ctl[0] >> 4) r = Range(ctl[0] >> 4)
r &= 0x03 r &= 0x03
return r, nil return r
} }
// ReadAcceleration reads the current acceleration from the device and returns // ReadAcceleration reads the current acceleration from the device and returns
@@ -121,17 +96,28 @@ func (d *Device) ReadRange() (r Range, err error) {
// and the sensor is not moving the returned value will be around 1000000 or // and the sensor is not moving the returned value will be around 1000000 or
// -1000000. // -1000000.
func (d *Device) ReadAcceleration() (int32, int32, int32, error) { func (d *Device) ReadAcceleration() (int32, int32, int32, error) {
rawX, rawY, rawZ := d.ReadRawAcceleration() x, y, z := d.ReadRawAcceleration()
x, y, z := normalizeRange(rawX, rawY, rawZ, d.r) divider := float32(1)
return x, y, z, nil switch d.r {
case RANGE_16_G:
divider = 1365
case RANGE_8_G:
divider = 4096
case RANGE_4_G:
divider = 8190
case RANGE_2_G:
divider = 16380
}
return int32(float32(x) / divider * 1000000), int32(float32(y) / divider * 1000000), int32(float32(z) / divider * 1000000), nil
} }
// ReadRawAcceleration returns the raw x, y and z axis from the LIS3DH // ReadRawAcceleration returns the raw x, y and z axis from the LIS3DH
func (d *Device) ReadRawAcceleration() (x int16, y int16, z int16) { func (d *Device) ReadRawAcceleration() (x int16, y int16, z int16) {
legacy.WriteRegister(d.bus, uint8(d.address), REG_OUT_X_L|0x80, nil) legacy.WriteRegister(d.bus, uint8(d.Address), REG_OUT_X_L|0x80, nil)
data := []byte{0, 0, 0, 0, 0, 0} data := []byte{0, 0, 0, 0, 0, 0}
d.bus.Tx(d.address, nil, data) d.bus.Tx(d.Address, nil, data)
x = int16((uint16(data[1]) << 8) | uint16(data[0])) x = int16((uint16(data[1]) << 8) | uint16(data[0]))
y = int16((uint16(data[3]) << 8) | uint16(data[2])) y = int16((uint16(data[3]) << 8) | uint16(data[2]))
@@ -139,68 +125,3 @@ func (d *Device) ReadRawAcceleration() (x int16, y int16, z int16) {
return return
} }
// Update the sensor values of the 'which' parameter. Only acceleration is
// supported at the moment.
func (d *Device) Update(which drivers.Measurement) error {
if which&drivers.Acceleration != 0 {
// Read raw acceleration values and store them in the driver.
err := legacy.WriteRegister(d.bus, uint8(d.address), REG_OUT_X_L|0x80, nil)
if err != nil {
return err
}
err = d.bus.Tx(d.address, nil, d.accel[:])
if err != nil {
return err
}
}
return nil
}
// Acceleration returns the last read acceleration in µg (micro-gravity).
// When one of the axes is pointing straight to Earth and the sensor is not
// moving the returned value will be around 1000000 or -1000000.
func (d *Device) Acceleration() (x, y, z int32) {
// Extract the raw 16-bit values.
rawX := int16((uint16(d.accel[1]) << 8) | uint16(d.accel[0]))
rawY := int16((uint16(d.accel[3]) << 8) | uint16(d.accel[2]))
rawZ := int16((uint16(d.accel[5]) << 8) | uint16(d.accel[4]))
// Normalize these values, to be in µg (micro-gravity).
return normalizeRange(rawX, rawY, rawZ, d.r)
}
// Convert raw 16-bit values to normalized 32-bit values while avoiding floats
// and divisions.
func normalizeRange(rawX, rawY, rawZ int16, r Range) (x, y, z int32) {
// We're going to convert the 16-bit raw values to values in the range
// -1000_000..1000_000. For now we're going to assume a range of 16G, we'll
// adjust that range later.
// The formula is derived as follows, and carefully selected to avoid
// overflow and integer divisions (the division will be optimized to a
// bitshift):
// x = x * 1000_000 / 2048
// x = x * (1000_000/64) / (2048/64)
// x = x * 15625 / 32
x = int32(rawX) * 15625 / 32
y = int32(rawY) * 15625 / 32
z = int32(rawZ) * 15625 / 32
// Now we need to normalize the three values, since we assumed 16G before.
shift := uint32(0)
switch r {
case RANGE_16_G:
shift = 0
case RANGE_8_G:
shift = 1
case RANGE_4_G:
shift = 2
case RANGE_2_G:
shift = 3
}
x >>= shift
y >>= shift
z >>= shift
return
}
+28 -35
View File
@@ -7,6 +7,7 @@ import (
"errors" "errors"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/legacy"
) )
type AccelRange uint8 type AccelRange uint8
@@ -27,7 +28,7 @@ type Device struct {
accelMultiplier int32 accelMultiplier int32
gyroMultiplier int32 gyroMultiplier int32
magMultiplier int32 magMultiplier int32
buf [7]uint8 // up to 6 bytes for read + 1 byte for the register address buf [6]uint8
} }
// Configuration for LSM9DS1 device. // Configuration for LSM9DS1 device.
@@ -60,15 +61,10 @@ func New(bus drivers.I2C) *Device {
// Case of boolean false and error nil means I2C is up, // Case of boolean false and error nil means I2C is up,
// but "who am I" responses have unexpected values. // but "who am I" responses have unexpected values.
func (d *Device) Connected() bool { func (d *Device) Connected() bool {
data, err := d.readBytes(d.AccelAddress, WHO_AM_I, 1) data1, data2 := d.buf[:1], d.buf[1:2]
if err != nil || data[0] != 0x68 { legacy.ReadRegister(d.bus, d.AccelAddress, WHO_AM_I, data1)
return false legacy.ReadRegister(d.bus, d.MagAddress, WHO_AM_I_M, data2)
} return data1[0] == 0x68 && data2[0] == 0x3D
data, err = d.readBytes(d.MagAddress, WHO_AM_I_M, 1)
if err != nil || data[0] != 0x3D {
return false
}
return true
} }
// ReadAcceleration reads the current acceleration from the device and returns // ReadAcceleration reads the current acceleration from the device and returns
@@ -76,7 +72,8 @@ func (d *Device) Connected() bool {
// and the sensor is not moving the returned value will be around 1000000 or // and the sensor is not moving the returned value will be around 1000000 or
// -1000000. // -1000000.
func (d *Device) ReadAcceleration() (x, y, z int32, err error) { func (d *Device) ReadAcceleration() (x, y, z int32, err error) {
data, err := d.readBytes(d.AccelAddress, OUT_X_L_XL, 6) data := d.buf[:6]
err = legacy.ReadRegister(d.bus, uint8(d.AccelAddress), OUT_X_L_XL, data)
if err != nil { if err != nil {
return return
} }
@@ -91,7 +88,8 @@ func (d *Device) ReadAcceleration() (x, y, z int32, err error) {
// rotation along one axis and while doing so integrate all values over time, // rotation along one axis and while doing so integrate all values over time,
// you would get a value close to 360000000. // you would get a value close to 360000000.
func (d *Device) ReadRotation() (x, y, z int32, err error) { func (d *Device) ReadRotation() (x, y, z int32, err error) {
data, err := d.readBytes(d.AccelAddress, OUT_X_L_G, 6) data := d.buf[:6]
err = legacy.ReadRegister(d.bus, uint8(d.AccelAddress), OUT_X_L_G, data)
if err != nil { if err != nil {
return return
} }
@@ -104,7 +102,8 @@ func (d *Device) ReadRotation() (x, y, z int32, err error) {
// ReadMagneticField reads the current magnetic field from the device and returns // ReadMagneticField reads the current magnetic field from the device and returns
// it in nT (nanotesla). 1 G (gauss) = 100_000 nT (nanotesla). // it in nT (nanotesla). 1 G (gauss) = 100_000 nT (nanotesla).
func (d *Device) ReadMagneticField() (x, y, z int32, err error) { func (d *Device) ReadMagneticField() (x, y, z int32, err error) {
data, err := d.readBytes(d.MagAddress, OUT_X_L_M, 6) data := d.buf[:6]
err = legacy.ReadRegister(d.bus, uint8(d.MagAddress), OUT_X_L_M, data)
if err != nil { if err != nil {
return return
} }
@@ -116,7 +115,8 @@ func (d *Device) ReadMagneticField() (x, y, z int32, err error) {
// ReadTemperature returns the temperature in Celsius milli degrees (°C/1000) // ReadTemperature returns the temperature in Celsius milli degrees (°C/1000)
func (d *Device) ReadTemperature() (t int32, err error) { func (d *Device) ReadTemperature() (t int32, err error) {
data, err := d.readBytes(d.AccelAddress, OUT_TEMP_L, 2) data := d.buf[:2]
err = legacy.ReadRegister(d.bus, uint8(d.AccelAddress), OUT_TEMP_L, data)
if err != nil { if err != nil {
return return
} }
@@ -167,16 +167,20 @@ func (d *Device) doConfigure(cfg Configuration) (err error) {
d.magMultiplier = 58 d.magMultiplier = 58
} }
data := d.buf[:1]
// Configure accelerometer // Configure accelerometer
// Sample rate & measurement range // Sample rate & measurement range
err = d.writeByte(d.AccelAddress, CTRL_REG6_XL, uint8(cfg.AccelSampleRate)<<5|uint8(cfg.AccelRange)<<3) data[0] = uint8(cfg.AccelSampleRate)<<5 | uint8(cfg.AccelRange)<<3
err = legacy.WriteRegister(d.bus, d.AccelAddress, CTRL_REG6_XL, data)
if err != nil { if err != nil {
return return
} }
// Configure gyroscope // Configure gyroscope
// Sample rate & measurement range // Sample rate & measurement range
err = d.writeByte(d.AccelAddress, CTRL_REG1_G, uint8(cfg.GyroSampleRate)<<5|uint8(cfg.GyroRange)<<3) data[0] = uint8(cfg.GyroSampleRate)<<5 | uint8(cfg.GyroRange)<<3
err = legacy.WriteRegister(d.bus, d.AccelAddress, CTRL_REG1_G, data)
if err != nil { if err != nil {
return return
} }
@@ -186,44 +190,33 @@ func (d *Device) doConfigure(cfg Configuration) (err error) {
// Temperature compensation enabled // Temperature compensation enabled
// High-performance mode XY axis // High-performance mode XY axis
// Sample rate // Sample rate
err = d.writeByte(d.MagAddress, CTRL_REG1_M, 0b10000000|0b01000000|uint8(cfg.MagSampleRate)<<2) data[0] = 0b10000000 | 0b01000000 | uint8(cfg.MagSampleRate)<<2
err = legacy.WriteRegister(d.bus, d.MagAddress, CTRL_REG1_M, data)
if err != nil { if err != nil {
return return
} }
// Measurement range // Measurement range
err = d.writeByte(d.MagAddress, CTRL_REG2_M, uint8(cfg.MagRange)<<5) data[0] = uint8(cfg.MagRange) << 5
err = legacy.WriteRegister(d.bus, d.MagAddress, CTRL_REG2_M, data)
if err != nil { if err != nil {
return return
} }
// Continuous-conversion mode // Continuous-conversion mode
// https://electronics.stackexchange.com/questions/237397/continuous-conversion-vs-single-conversion-mode // https://electronics.stackexchange.com/questions/237397/continuous-conversion-vs-single-conversion-mode
err = d.writeByte(d.MagAddress, CTRL_REG3_M, 0b00000000) data[0] = 0b00000000
err = legacy.WriteRegister(d.bus, d.MagAddress, CTRL_REG3_M, data)
if err != nil { if err != nil {
return return
} }
// High-performance mode Z axis // High-performance mode Z axis
err = d.writeByte(d.MagAddress, CTRL_REG4_M, 0b00001000) data[0] = 0b00001000
err = legacy.WriteRegister(d.bus, d.MagAddress, CTRL_REG4_M, data)
if err != nil { if err != nil {
return return
} }
return nil return nil
} }
func (d *Device) readBytes(addr, reg, size uint8) ([]byte, error) {
d.buf[0] = reg
err := d.bus.Tx(uint16(addr), d.buf[0:1], d.buf[1:size+1])
if err != nil {
return nil, err
}
return d.buf[1 : size+1], nil
}
func (d *Device) writeByte(addr, reg, value uint8) error {
d.buf[0] = reg
d.buf[1] = value
return d.bus.Tx(uint16(addr), d.buf[0:2], nil)
}
+4 -4
View File
@@ -3,9 +3,9 @@ package max6675
import ( import (
"errors" "errors"
"machine"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
// ErrThermocoupleOpen is returned when the thermocouple input is open. // ErrThermocoupleOpen is returned when the thermocouple input is open.
@@ -14,16 +14,16 @@ var ErrThermocoupleOpen = errors.New("thermocouple input open")
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
} }
// Create a new Device to read from a MAX6675 thermocouple. // Create a new Device to read from a MAX6675 thermocouple.
// Pins must be configured before use. Frequency for SPI // Pins must be configured before use. Frequency for SPI
// should be 4.3MHz maximum. // should be 4.3MHz maximum.
func NewDevice(bus drivers.SPI, cs machine.Pin) *Device { func NewDevice(bus drivers.SPI, cs pin.Output) *Device {
return &Device{ return &Device{
bus: bus, bus: bus,
cs: cs, cs: cs.Set,
} }
} }
+15 -11
View File
@@ -3,31 +3,35 @@
package max72xx package max72xx
import ( import (
"machine"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
configurePins func()
} }
// NewDriver creates a new max7219 connection. The SPI wire must already be configured // NewDriver creates a new max7219 connection. The SPI wire must already be configured
// The SPI frequency must not be higher than 10MHz. // The SPI frequency must not be higher than 10MHz.
// parameter cs: the datasheet also refers to this pin as "load" pin. // parameter cs: the datasheet also refers to this pin as "load" pin.
func NewDevice(bus drivers.SPI, cs machine.Pin) *Device { func NewDevice(bus drivers.SPI, cs pin.Output) *Device {
return &Device{ return &Device{
bus: bus, bus: bus,
cs: cs, cs: cs.Set,
configurePins: func() {
pin.ConfigureOutput(cs)
},
} }
} }
// Configure setups the pins. // Configure setups the pins.
func (driver *Device) Configure() { func (driver *Device) Configure() {
outPutConfig := machine.PinConfig{Mode: machine.PinOutput} if driver.configurePins == nil {
panic(pin.ErrConfigBeforeInstantiated)
driver.cs.Configure(outPutConfig) }
driver.configurePins()
} }
// SetScanLimit sets the scan limit. Maximum is 8. // SetScanLimit sets the scan limit. Maximum is 8.
@@ -89,8 +93,8 @@ func (driver *Device) writeByte(data byte) {
// WriteCommand write data to a given register. // WriteCommand write data to a given register.
func (driver *Device) WriteCommand(register, data byte) { func (driver *Device) WriteCommand(register, data byte) {
driver.cs.Low() driver.cs(false)
driver.writeByte(register) driver.writeByte(register)
driver.writeByte(data) driver.writeByte(data)
driver.cs.High() driver.cs(true)
} }
+15 -8
View File
@@ -8,18 +8,19 @@ package mcp2515 // import "tinygo.org/x/drivers/mcp2515"
import ( import (
"errors" "errors"
"fmt" "fmt"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
// Device wraps MCP2515 SPI CAN Module. // Device wraps MCP2515 SPI CAN Module.
type Device struct { type Device struct {
spi SPI spi SPI
cs machine.Pin cs pin.OutputFunc
msg *CANMsg msg *CANMsg
mcpMode byte mcpMode byte
configurePins func()
} }
// CANMsg stores CAN message fields. // CANMsg stores CAN message fields.
@@ -36,15 +37,18 @@ const (
) )
// New returns a new MCP2515 driver. Pass in a fully configured SPI bus. // New returns a new MCP2515 driver. Pass in a fully configured SPI bus.
func New(b drivers.SPI, csPin machine.Pin) *Device { func New(b drivers.SPI, csPin pin.Output) *Device {
d := &Device{ d := &Device{
spi: SPI{ spi: SPI{
bus: b, bus: b,
tx: make([]byte, 0, bufferSize), tx: make([]byte, 0, bufferSize),
rx: make([]byte, 0, bufferSize), rx: make([]byte, 0, bufferSize),
}, },
cs: csPin, cs: csPin.Set,
msg: &CANMsg{}, msg: &CANMsg{},
configurePins: func() {
pin.ConfigureOutput(csPin)
},
} }
return d return d
@@ -52,7 +56,10 @@ func New(b drivers.SPI, csPin machine.Pin) *Device {
// Configure sets up the device for communication. // Configure sets up the device for communication.
func (d *Device) Configure() { func (d *Device) Configure() {
d.cs.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.configurePins == nil {
panic(pin.ErrConfigBeforeInstantiated)
}
d.configurePins()
} }
const beginTimeoutValue int = 10 const beginTimeoutValue int = 10
+8 -8
View File
@@ -6,18 +6,18 @@ package pcd8544 // import "tinygo.org/x/drivers/pcd8544"
import ( import (
"errors" "errors"
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
// Device wraps an SPI connection. // Device wraps an SPI connection.
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
rstPin machine.Pin rstPin pin.OutputFunc
scePin machine.Pin scePin pin.OutputFunc
buffer []byte buffer []byte
width int16 width int16
height int16 height int16
@@ -30,12 +30,12 @@ type Config struct {
} }
// New creates a new PCD8544 connection. The SPI bus must already be configured. // New creates a new PCD8544 connection. The SPI bus must already be configured.
func New(bus drivers.SPI, dcPin, rstPin, scePin machine.Pin) *Device { func New(bus drivers.SPI, dcPin, rstPin, scePin pin.Output) *Device {
return &Device{ return &Device{
bus: bus, bus: bus,
dcPin: dcPin, dcPin: dcPin.Set,
rstPin: rstPin, rstPin: rstPin.Set,
scePin: scePin, scePin: scePin.Set,
} }
} }
+23 -17
View File
@@ -2,7 +2,7 @@
package shiftregister package shiftregister
import ( import (
"machine" "tinygo.org/x/drivers/internal/pin"
) )
type NumberBit int8 type NumberBit int8
@@ -16,9 +16,10 @@ const (
// Device holds pin number // Device holds pin number
type Device struct { type Device struct {
latch, clock, out machine.Pin // IC wiring latch, clock, out pin.OutputFunc // IC wiring
bits NumberBit // Pin number config func()
mask uint32 // keep all pins state bits NumberBit // Pin number
mask uint32 // keep all pins state
} }
// ShiftPin is the implementation of the ShiftPin interface. // ShiftPin is the implementation of the ShiftPin interface.
@@ -29,35 +30,40 @@ type ShiftPin struct {
} }
// New returns a new shift output register device // New returns a new shift output register device
func New(Bits NumberBit, Latch, Clock, Out machine.Pin) *Device { func New(Bits NumberBit, Latch, Clock, Out pin.Output) *Device {
return &Device{ return &Device{
latch: Latch, latch: Latch.Set,
clock: Clock, clock: Clock.Set,
out: Out, out: Out.Set,
bits: Bits, bits: Bits,
config: func() {
pin.ConfigureOutput(Latch)
pin.ConfigureOutput(Clock)
pin.ConfigureOutput(Out)
},
} }
} }
// Configure set hardware configuration // Configure set hardware configuration
func (d *Device) Configure() { func (d *Device) Configure() {
d.latch.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.config == nil {
d.clock.Configure(machine.PinConfig{Mode: machine.PinOutput}) panic(pin.ErrConfigBeforeInstantiated)
d.out.Configure(machine.PinConfig{Mode: machine.PinOutput}) }
d.latch.High() d.latch(true)
} }
// WriteMask applies mask's bits to register's outputs pin // WriteMask applies mask's bits to register's outputs pin
// mask's MSB set Q1, LSB set Q8 (for 8 bits mask) // mask's MSB set Q1, LSB set Q8 (for 8 bits mask)
func (d *Device) WriteMask(mask uint32) { func (d *Device) WriteMask(mask uint32) {
d.mask = mask // Keep the mask for individual addressing d.mask = mask // Keep the mask for individual addressing
d.latch.Low() d.latch(false)
for i := 0; i < int(d.bits); i++ { for i := 0; i < int(d.bits); i++ {
d.clock.Low() d.clock(false)
d.out.Set(mask&1 != 0) d.out(mask&1 != 0)
mask = mask >> 1 mask = mask >> 1
d.clock.High() d.clock(true)
} }
d.latch.High() d.latch(true)
} }
// GetShiftPin return an individually addressable pin // GetShiftPin return an individually addressable pin
+2
View File
@@ -1,3 +1,5 @@
//go:build baremetal
package ssd1289 package ssd1289
import "machine" import "machine"
+18 -18
View File
@@ -5,8 +5,9 @@ package ssd1289
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers/internal/pin"
) )
type Bus interface { type Bus interface {
@@ -14,33 +15,32 @@ type Bus interface {
} }
type Device struct { type Device struct {
rs machine.Pin rs pin.OutputFunc
wr machine.Pin wr pin.OutputFunc
cs machine.Pin cs pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
bus Bus bus Bus
} }
const width = int16(240) const width = int16(240)
const height = int16(320) const height = int16(320)
func New(rs machine.Pin, wr machine.Pin, cs machine.Pin, rst machine.Pin, bus Bus) Device { func New(rs pin.Output, wr pin.Output, cs pin.Output, rst pin.Output, bus Bus) Device {
d := Device{ d := Device{
rs: rs, rs: rs.Set,
wr: wr, wr: wr.Set,
cs: cs, cs: cs.Set,
rst: rst, rst: rst.Set,
bus: bus, bus: bus,
} }
pin.ConfigureOutput(rs)
pin.ConfigureOutput(wr)
pin.ConfigureOutput(cs)
pin.ConfigureOutput(rst)
rs.Configure(machine.PinConfig{Mode: machine.PinOutput}) d.cs.High()
wr.Configure(machine.PinConfig{Mode: machine.PinOutput}) d.rst.High()
cs.Configure(machine.PinConfig{Mode: machine.PinOutput}) d.wr.High()
rst.Configure(machine.PinConfig{Mode: machine.PinOutput})
cs.High()
rst.High()
wr.High()
return d return d
} }
+11 -10
View File
@@ -11,6 +11,7 @@ import (
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Model uint8 type Model uint8
@@ -19,9 +20,9 @@ type Rotation uint8
// Device wraps an SPI connection. // Device wraps an SPI connection.
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
resetPin machine.Pin resetPin pin.OutputFunc
csPin machine.Pin csPin pin.OutputFunc
width int16 width int16
height int16 height int16
batchLength int16 batchLength int16
@@ -37,14 +38,14 @@ type Config struct {
// New creates a new SSD1331 connection. The SPI wire must already be configured. // New creates a new SSD1331 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin machine.Pin) Device { func New(bus drivers.SPI, resetPin, dcPin, csPin machine.Pin) Device {
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(resetPin)
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
return Device{ return Device{
bus: bus, bus: bus,
dcPin: dcPin, dcPin: dcPin.Set,
resetPin: resetPin, resetPin: resetPin.Set,
csPin: csPin, csPin: csPin.Set,
} }
} }
@@ -251,7 +252,7 @@ func (d *Device) Data(data uint8) {
// Tx sends data to the display // Tx sends data to the display
func (d *Device) Tx(data []byte, isCommand bool) { func (d *Device) Tx(data []byte, isCommand bool) {
d.dcPin.Set(!isCommand) d.dcPin(!isCommand)
d.bus.Tx(data, nil) d.bus.Tx(data, nil)
} }
+31 -24
View File
@@ -6,10 +6,10 @@ package ssd1351 // import "tinygo.org/x/drivers/ssd1351"
import ( import (
"errors" "errors"
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
var ( var (
@@ -19,17 +19,18 @@ var (
// Device wraps an SPI connection. // Device wraps an SPI connection.
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
resetPin machine.Pin resetPin pin.OutputFunc
csPin machine.Pin csPin pin.OutputFunc
enPin machine.Pin enPin pin.OutputFunc
rwPin machine.Pin rwPin pin.OutputFunc
width int16 configurePins func()
height int16 width int16
rowOffset int16 height int16
columnOffset int16 rowOffset int16
bufferLength int16 columnOffset int16
bufferLength int16
} }
// Config is the configuration for the display // Config is the configuration for the display
@@ -41,19 +42,29 @@ type Config struct {
} }
// New creates a new SSD1351 connection. The SPI wire must already be configured. // New creates a new SSD1351 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin, enPin, rwPin machine.Pin) Device { func New(bus drivers.SPI, resetPin, dcPin, csPin, enPin, rwPin pin.Output) Device {
return Device{ return Device{
bus: bus, bus: bus,
dcPin: dcPin, dcPin: dcPin.Set,
resetPin: resetPin, resetPin: resetPin.Set,
csPin: csPin, csPin: csPin.Set,
enPin: enPin, enPin: enPin.Set,
rwPin: rwPin, rwPin: rwPin.Set,
configurePins: func() {
pin.ConfigureOutput(dcPin)
pin.ConfigureOutput(resetPin)
pin.ConfigureOutput(csPin)
pin.ConfigureOutput(enPin)
pin.ConfigureOutput(rwPin)
},
} }
} }
// Configure initializes the display with default configuration // Configure initializes the display with default configuration
func (d *Device) Configure(cfg Config) { func (d *Device) Configure(cfg Config) {
if d.configurePins == nil {
panic(pin.ErrConfigBeforeInstantiated)
}
if cfg.Width == 0 { if cfg.Width == 0 {
cfg.Width = 128 cfg.Width = 128
} }
@@ -73,11 +84,7 @@ func (d *Device) Configure(cfg Config) {
} }
// configure GPIO pins // configure GPIO pins
d.dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) d.configurePins()
d.resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.csPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.enPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.rwPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
// reset the device // reset the device
d.resetPin.High() d.resetPin.High()
@@ -278,7 +285,7 @@ func (d *Device) Data(data uint8) {
// Tx sends data to the display // Tx sends data to the display
func (d *Device) Tx(data []byte, isCommand bool) { func (d *Device) Tx(data []byte, isCommand bool) {
d.dcPin.Set(!isCommand) d.dcPin(!isCommand)
d.csPin.Low() d.csPin.Low()
d.bus.Tx(data, nil) d.bus.Tx(data, nil)
d.csPin.High() d.csPin.High()
+18 -18
View File
@@ -5,12 +5,12 @@ package st7735 // import "tinygo.org/x/drivers/st7735"
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"errors" "errors"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/pixel" "tinygo.org/x/drivers/pixel"
) )
@@ -39,10 +39,10 @@ type Device = DeviceOf[pixel.RGB565BE]
// formats. // formats.
type DeviceOf[T Color] struct { type DeviceOf[T Color] struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
resetPin machine.Pin resetPin pin.OutputFunc
csPin machine.Pin csPin pin.OutputFunc
blPin machine.Pin blPin pin.OutputFunc
width int16 width int16
height int16 height int16
columnOffset int16 columnOffset int16
@@ -65,23 +65,23 @@ type Config struct {
} }
// New creates a new ST7735 connection. The SPI wire must already be configured. // New creates a new ST7735 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) Device { func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) Device {
return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin) return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
} }
// NewOf creates a new ST7735 connection with a particular pixel format. The SPI // NewOf creates a new ST7735 connection with a particular pixel format. The SPI
// wire must already be configured. // wire must already be configured.
func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) DeviceOf[T] { func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) DeviceOf[T] {
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(resetPin)
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(blPin)
return DeviceOf[T]{ return DeviceOf[T]{
bus: bus, bus: bus,
dcPin: dcPin, dcPin: dcPin.Set,
resetPin: resetPin, resetPin: resetPin.Set,
csPin: csPin, csPin: csPin.Set,
blPin: blPin, blPin: blPin.Set,
} }
} }
@@ -423,7 +423,7 @@ func (d *DeviceOf[T]) Data(data uint8) {
// Tx sends data to the display // Tx sends data to the display
func (d *DeviceOf[T]) Tx(data []byte, isCommand bool) { func (d *DeviceOf[T]) Tx(data []byte, isCommand bool) {
d.dcPin.Set(!isCommand) d.dcPin(!isCommand)
d.bus.Tx(data, nil) d.bus.Tx(data, nil)
} }
@@ -438,9 +438,9 @@ func (d *DeviceOf[T]) Size() (w, h int16) {
// EnableBacklight enables or disables the backlight // EnableBacklight enables or disables the backlight
func (d *DeviceOf[T]) EnableBacklight(enable bool) { func (d *DeviceOf[T]) EnableBacklight(enable bool) {
if enable { if enable {
d.blPin.High() d.blPin(true)
} else { } else {
d.blPin.Low() d.blPin(false)
} }
} }
+21 -17
View File
@@ -7,13 +7,13 @@ package st7789 // import "tinygo.org/x/drivers/st7789"
import ( import (
"image/color" "image/color"
"machine"
"math" "math"
"time" "time"
"errors" "errors"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/pixel" "tinygo.org/x/drivers/pixel"
) )
@@ -46,10 +46,10 @@ type Device = DeviceOf[pixel.RGB565BE]
// formats. // formats.
type DeviceOf[T Color] struct { type DeviceOf[T Color] struct {
bus drivers.SPI bus drivers.SPI
dcPin machine.Pin dcPin pin.OutputFunc
resetPin machine.Pin resetPin pin.OutputFunc
csPin machine.Pin csPin pin.OutputFunc
blPin machine.Pin blPin pin.OutputFunc
width int16 width int16
height int16 height int16
columnOffsetCfg int16 columnOffsetCfg int16
@@ -83,23 +83,27 @@ type Config struct {
} }
// New creates a new ST7789 connection. The SPI wire must already be configured. // 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 drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) Device {
return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin) return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
} }
// NewOf creates a new ST7789 connection with a particular pixel format. The SPI // NewOf creates a new ST7789 connection with a particular pixel format. The SPI
// wire must already be configured. // wire must already be configured.
func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) DeviceOf[T] { func NewOf[T Color](bus drivers.SPI, resetPin, dcPin, csPin, blPin pin.Output) DeviceOf[T] {
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(resetPin)
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(blPin)
var cs pin.OutputFunc
if !pin.IsNotPin(csPin) {
cs = csPin.Set
}
return DeviceOf[T]{ return DeviceOf[T]{
bus: bus, bus: bus,
dcPin: dcPin, dcPin: dcPin.Set,
resetPin: resetPin, resetPin: resetPin.Set,
csPin: csPin, csPin: cs,
blPin: blPin, blPin: blPin.Set,
} }
} }
@@ -229,7 +233,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 // startWrite must be called at the beginning of all exported methods to set the
// chip select pin low. // chip select pin low.
func (d *DeviceOf[T]) startWrite() { func (d *DeviceOf[T]) startWrite() {
if d.csPin != machine.NoPin { if d.csPin != nil {
d.csPin.Low() d.csPin.Low()
} }
} }
@@ -237,7 +241,7 @@ func (d *DeviceOf[T]) startWrite() {
// endWrite must be called at the end of all exported methods to set the chip // endWrite must be called at the end of all exported methods to set the chip
// select pin high. // select pin high.
func (d *DeviceOf[T]) endWrite() { func (d *DeviceOf[T]) endWrite() {
if d.csPin != machine.NoPin { if d.csPin != nil {
d.csPin.High() d.csPin.High()
} }
} }
+6 -6
View File
@@ -6,10 +6,10 @@ package sx127x
import ( import (
"errors" "errors"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/lora" "tinygo.org/x/drivers/lora"
) )
@@ -22,7 +22,7 @@ const (
// Device wraps an SPI connection to a SX127x device. // Device wraps an SPI connection to a SX127x device.
type Device struct { type Device struct {
spi drivers.SPI // SPI bus for module communication spi drivers.SPI // SPI bus for module communication
rstPin machine.Pin // GPIO for reset rstPin pin.OutputFunc // GPIO for reset
radioEventChan chan lora.RadioEvent // Channel for Receiving events radioEventChan chan lora.RadioEvent // Channel for Receiving events
loraConf lora.Config // Current Lora configuration loraConf lora.Config // Current Lora configuration
controller RadioController // to manage interactions with the radio controller RadioController // to manage interactions with the radio
@@ -43,10 +43,10 @@ func (d *Device) GetRadioEventChan() chan lora.RadioEvent {
} }
// New creates a new SX127x connection. The SPI bus must already be configured. // New creates a new SX127x connection. The SPI bus must already be configured.
func New(spi drivers.SPI, rstPin machine.Pin) *Device { func New(spi drivers.SPI, rstPin pin.Output) *Device {
k := Device{ k := Device{
spi: spi, spi: spi,
rstPin: rstPin, rstPin: rstPin.Set,
radioEventChan: make(chan lora.RadioEvent, RADIOEVENTCHAN_SIZE), radioEventChan: make(chan lora.RadioEvent, RADIOEVENTCHAN_SIZE),
spiTxBuf: make([]byte, SPI_BUFFER_SIZE), spiTxBuf: make([]byte, SPI_BUFFER_SIZE),
spiRxBuf: make([]byte, SPI_BUFFER_SIZE), spiRxBuf: make([]byte, SPI_BUFFER_SIZE),
@@ -67,9 +67,9 @@ func (d *Device) SetRadioController(rc RadioController) error {
// Reset re-initialize the sx127x device // Reset re-initialize the sx127x device
func (d *Device) Reset() { func (d *Device) Reset() {
d.rstPin.Low() d.rstPin(false)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
d.rstPin.High() d.rstPin(true)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
+5 -11
View File
@@ -11,7 +11,6 @@ import (
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/legacy"
"tinygo.org/x/drivers/internal/pin" "tinygo.org/x/drivers/internal/pin"
"tinygo.org/x/drivers/pixel" "tinygo.org/x/drivers/pixel"
) )
@@ -35,7 +34,7 @@ type Device struct {
cs pin.OutputFunc cs pin.OutputFunc
dc pin.OutputFunc dc pin.OutputFunc
rst pin.OutputFunc rst pin.OutputFunc
isBusy pin.InputFunc isBusy drivers.PinInput
width int16 width int16
height int16 height int16
buffer []uint8 buffer []uint8
@@ -50,16 +49,11 @@ type Device struct {
type Speed uint8 type Speed uint8
// New returns a new uc8151 driver. Pass in a fully configured SPI bus. // New returns a new uc8151 driver. Pass in a fully configured SPI bus.
// Pins passed in must be configured beforehand.
func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device { func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
// For backwards compatibility. pin.ConfigureOutput(csPin)
// This driver used to configure pins, pin.ConfigureOutput(dcPin)
// so leave in to not break users. pin.ConfigureOutput(rstPin)
// May be removed in future so try not to depend on it! pin.ConfigureInput(busyPin)
legacy.ConfigurePinOut(csPin)
legacy.ConfigurePinOut(dcPin)
legacy.ConfigurePinOut(rstPin)
legacy.ConfigurePinInput(busyPin)
return Device{ return Device{
bus: bus, bus: bus,
cs: csPin.Set, cs: csPin.Set,
+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. // 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. // Update this value before release of new version of software.
const Version = "0.33.0" const Version = "0.32.0"
+32 -23
View File
@@ -12,6 +12,9 @@ import (
"image/color" "image/color"
"machine" "machine"
"time" "time"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Config struct { type Config struct {
@@ -22,14 +25,14 @@ type Config struct {
} }
type Device struct { type Device struct {
bus *machine.SPI bus *machine.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
configurePins func()
buffer []uint8 buffer []uint8
rotation Rotation rotation Rotation
} }
type Rotation uint8 type Rotation uint8
@@ -79,22 +82,28 @@ var partialRefresh = [159]uint8{
} }
// New returns a new epd1in54 driver. Pass in a fully configured SPI bus. // New returns a new epd1in54 driver. Pass in a fully configured SPI bus.
func New(bus *machine.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device { func New(bus *machine.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
return Device{ return Device{
buffer: make([]uint8, (uint32(Width)*uint32(Height))/8), buffer: make([]uint8, (uint32(Width)*uint32(Height))/8),
bus: bus, bus: bus,
cs: csPin, cs: csPin.Set,
dc: dcPin, dc: dcPin.Set,
rst: rstPin, rst: rstPin.Set,
busy: busyPin, isBusy: busyPin.Get,
configurePins: func() {
pin.ConfigureOutput(csPin)
pin.ConfigureOutput(dcPin)
pin.ConfigureOutput(rstPin)
pin.ConfigureInput(busyPin)
},
} }
} }
func (d *Device) LDirInit(cfg Config) { func (d *Device) LDirInit(cfg Config) {
d.cs.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.configurePins == nil {
d.rst.Configure(machine.PinConfig{Mode: machine.PinOutput}) panic(pin.ErrConfigBeforeInstantiated)
d.dc.Configure(machine.PinConfig{Mode: machine.PinOutput}) }
d.busy.Configure(machine.PinConfig{Mode: machine.PinInput}) d.configurePins()
d.bus.Configure(machine.SPIConfig{ d.bus.Configure(machine.SPIConfig{
Frequency: 2000000, Frequency: 2000000,
@@ -150,10 +159,10 @@ func (d *Device) LDirInit(cfg Config) {
} }
func (d *Device) HDirInit(cfg Config) { func (d *Device) HDirInit(cfg Config) {
d.cs.Configure(machine.PinConfig{Mode: machine.PinOutput}) if d.configurePins == nil {
d.rst.Configure(machine.PinConfig{Mode: machine.PinOutput}) panic(pin.ErrConfigBeforeInstantiated)
d.dc.Configure(machine.PinConfig{Mode: machine.PinOutput}) }
d.busy.Configure(machine.PinConfig{Mode: machine.PinInput}) d.configurePins()
d.bus.Configure(machine.SPIConfig{ d.bus.Configure(machine.SPIConfig{
Frequency: 2000000, Frequency: 2000000,
@@ -369,7 +378,7 @@ func (d *Device) Clear() {
// WaitUntilIdle waits until the display is ready // WaitUntilIdle waits until the display is ready
func (d *Device) WaitUntilIdle() { func (d *Device) WaitUntilIdle() {
for d.busy.Get() { for d.isBusy() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
time.Sleep(200 * time.Millisecond) time.Sleep(200 * time.Millisecond)
@@ -377,7 +386,7 @@ func (d *Device) WaitUntilIdle() {
// IsBusy returns the busy status of the display // IsBusy returns the busy status of the display
func (d *Device) IsBusy() bool { func (d *Device) IsBusy() bool {
return d.busy.Get() return d.isBusy()
} }
// ClearBuffer sets the buffer to 0xFF (white) // ClearBuffer sets the buffer to 0xFF (white)
+17 -17
View File
@@ -6,10 +6,10 @@ package epd2in13 // import "tinygo.org/x/drivers/waveshare-epd/epd2in13"
import ( import (
"errors" "errors"
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Config struct { type Config struct {
@@ -21,10 +21,10 @@ type Config struct {
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
logicalWidth int16 logicalWidth int16
width int16 width int16
height int16 height int16
@@ -53,17 +53,17 @@ var lutPartialUpdate = [30]uint8{
} }
// New returns a new epd2in13x driver. Pass in a fully configured SPI bus. // New returns a new epd2in13x driver. Pass in a fully configured SPI bus.
func New(bus drivers.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device { func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
rstPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(rstPin)
busyPin.Configure(machine.PinConfig{Mode: machine.PinInput}) pin.ConfigureInput(busyPin)
return Device{ return Device{
bus: bus, bus: bus,
cs: csPin, cs: csPin.Set,
dc: dcPin, dc: dcPin.Set,
rst: rstPin, rst: rstPin.Set,
busy: busyPin, isBusy: busyPin.Get,
} }
} }
@@ -298,14 +298,14 @@ func (d *Device) setMemoryPointer(x int16, y int16) {
// WaitUntilIdle waits until the display is ready // WaitUntilIdle waits until the display is ready
func (d *Device) WaitUntilIdle() { func (d *Device) WaitUntilIdle() {
for d.busy.Get() { for d.isBusy() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
} }
// IsBusy returns the busy status of the display // IsBusy returns the busy status of the display
func (d *Device) IsBusy() bool { func (d *Device) IsBusy() bool {
return d.busy.Get() return d.isBusy()
} }
// ClearBuffer sets the buffer to 0xFF (white) // ClearBuffer sets the buffer to 0xFF (white)
+17 -17
View File
@@ -6,10 +6,10 @@ package epd2in13x // import "tinygo.org/x/drivers/waveshare-epd/epd2in13x"
import ( import (
"errors" "errors"
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Config struct { type Config struct {
@@ -20,10 +20,10 @@ type Config struct {
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
width int16 width int16
height int16 height int16
buffer [][]uint8 buffer [][]uint8
@@ -33,17 +33,17 @@ type Device struct {
type Color uint8 type Color uint8
// New returns a new epd2in13x driver. Pass in a fully configured SPI bus. // New returns a new epd2in13x driver. Pass in a fully configured SPI bus.
func New(bus drivers.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device { func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
rstPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(rstPin)
busyPin.Configure(machine.PinConfig{Mode: machine.PinInput}) pin.ConfigureInput(busyPin)
return Device{ return Device{
bus: bus, bus: bus,
cs: csPin, cs: csPin.Set,
dc: dcPin, dc: dcPin.Set,
rst: rstPin, rst: rstPin.Set,
busy: busyPin, isBusy: busyPin.Get,
} }
} }
@@ -277,14 +277,14 @@ func (d *Device) ClearDisplay() {
// WaitUntilIdle waits until the display is ready // WaitUntilIdle waits until the display is ready
func (d *Device) WaitUntilIdle() { func (d *Device) WaitUntilIdle() {
for !d.busy.Get() { for !d.isBusy() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
} }
// IsBusy returns the busy status of the display // IsBusy returns the busy status of the display
func (d *Device) IsBusy() bool { func (d *Device) IsBusy() bool {
return d.busy.Get() return d.isBusy()
} }
// ClearBuffer sets the buffer to 0xFF (white) // ClearBuffer sets the buffer to 0xFF (white)
+7 -29
View File
@@ -5,10 +5,10 @@ package epd2in66b
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
const ( const (
@@ -18,19 +18,12 @@ const (
const Baudrate = 4_000_000 // 4 MHz const Baudrate = 4_000_000 // 4 MHz
type Config struct {
ResetPin machine.Pin
DataPin machine.Pin
ChipSelectPin machine.Pin
BusyPin machine.Pin
}
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
blackBuffer []byte blackBuffer []byte
redBuffer []byte redBuffer []byte
@@ -50,21 +43,6 @@ func New(bus drivers.SPI) Device {
} }
} }
// Configure configures the device and its pins.
func (d *Device) Configure(c Config) error {
d.cs = c.ChipSelectPin
d.dc = c.DataPin
d.rst = c.ResetPin
d.busy = c.BusyPin
d.cs.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.dc.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.rst.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.busy.Configure(machine.PinConfig{Mode: machine.PinInput})
return nil
}
func (d *Device) Size() (x, y int16) { func (d *Device) Size() (x, y int16) {
return displayWidth, displayHeight return displayWidth, displayHeight
} }
@@ -229,7 +207,7 @@ func (d *Device) WaitUntilIdle() {
// give it some time to get busy // give it some time to get busy
time.Sleep(50 * time.Millisecond) time.Sleep(50 * time.Millisecond)
for d.busy.Get() { // high = busy for d.isBusy() { // high = busy
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
} }
+30
View File
@@ -0,0 +1,30 @@
//go:build baremetal
package epd2in66b
import "machine"
type Config struct {
ResetPin machine.Pin
DataPin machine.Pin
ChipSelectPin machine.Pin
BusyPin machine.Pin
}
// Configure configures the device and its pins.
func (d *Device) Configure(c Config) error {
cs := c.ChipSelectPin
dc := c.DataPin
rst := c.ResetPin
busy := c.BusyPin
cs.Configure(machine.PinConfig{Mode: machine.PinOutput})
dc.Configure(machine.PinConfig{Mode: machine.PinOutput})
rst.Configure(machine.PinConfig{Mode: machine.PinOutput})
busy.Configure(machine.PinConfig{Mode: machine.PinInput})
d.cs = cs.Set
d.dc = dc.Set
d.rst = rst.Set
d.isBusy = busy.Get
return nil
}
+18 -18
View File
@@ -13,10 +13,10 @@ package epd2in9 // import "tinygo.org/x/drivers/waveshare-epd/epd2in9"
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Config struct { type Config struct {
@@ -28,10 +28,10 @@ type Config struct {
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
logicalWidth int16 logicalWidth int16
width int16 width int16
height int16 height int16
@@ -61,17 +61,17 @@ var lutPartialUpdate = [30]uint8{
} }
// New returns a new epd2in9 driver. Pass in a fully configured SPI bus. // New returns a new epd2in9 driver. Pass in a fully configured SPI bus.
func New(bus drivers.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device { func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
rstPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(rstPin)
busyPin.Configure(machine.PinConfig{Mode: machine.PinInput}) pin.ConfigureInput(busyPin)
return Device{ return Device{
bus: bus, bus: bus,
cs: csPin, cs: csPin.Set,
dc: dcPin, dc: dcPin.Set,
rst: rstPin, rst: rstPin.Set,
busy: busyPin, isBusy: busyPin.Get,
} }
} }
@@ -122,7 +122,7 @@ func (d *Device) Configure(cfg Config) {
d.SendCommand(DATA_ENTRY_MODE_SETTING) d.SendCommand(DATA_ENTRY_MODE_SETTING)
d.SendData(0x03) // X increment; Y increment d.SendData(0x03) // X increment; Y increment
d.SetLUT(true) d.SetLUT.High()
} }
// Reset resets the device // Reset resets the device
@@ -245,14 +245,14 @@ func (d *Device) setMemoryPointer(x int16, y int16) {
// WaitUntilIdle waits until the display is ready // WaitUntilIdle waits until the display is ready
func (d *Device) WaitUntilIdle() { func (d *Device) WaitUntilIdle() {
for d.busy.Get() { for d.isBusy() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
} }
// IsBusy returns the busy status of the display // IsBusy returns the busy status of the display
func (d *Device) IsBusy() bool { func (d *Device) IsBusy() bool {
return d.busy.Get() return d.isBusy()
} }
// ClearBuffer sets the buffer to 0xFF (white) // ClearBuffer sets the buffer to 0xFF (white)
+17 -17
View File
@@ -10,10 +10,10 @@ package epd4in2
import ( import (
"image/color" "image/color"
"machine"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
"tinygo.org/x/drivers/internal/pin"
) )
type Config struct { type Config struct {
@@ -25,10 +25,10 @@ type Config struct {
type Device struct { type Device struct {
bus drivers.SPI bus drivers.SPI
cs machine.Pin cs pin.OutputFunc
dc machine.Pin dc pin.OutputFunc
rst machine.Pin rst pin.OutputFunc
busy machine.Pin isBusy drivers.PinInput
logicalWidth int16 logicalWidth int16
width int16 width int16
height int16 height int16
@@ -40,17 +40,17 @@ type Device struct {
type Rotation uint8 type Rotation uint8
// New returns a new epd4in2 driver. Pass in a fully configured SPI bus. // New returns a new epd4in2 driver. Pass in a fully configured SPI bus.
func New(bus drivers.SPI, csPin, dcPin, rstPin, busyPin machine.Pin) Device { func New(bus drivers.SPI, csPin, dcPin, rstPin pin.Output, busyPin pin.Input) Device {
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(csPin)
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(dcPin)
rstPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) pin.ConfigureOutput(rstPin)
busyPin.Configure(machine.PinConfig{Mode: machine.PinInput}) pin.ConfigureInput(busyPin)
return Device{ return Device{
bus: bus, bus: bus,
cs: csPin, cs: csPin.Set,
dc: dcPin, dc: dcPin.Set,
rst: rstPin, rst: rstPin.Set,
busy: busyPin, isBusy: busyPin.Get,
} }
} }
@@ -311,14 +311,14 @@ func (d *Device) ClearDisplay() {
// WaitUntilIdle waits until the display is ready // WaitUntilIdle waits until the display is ready
func (d *Device) WaitUntilIdle() { func (d *Device) WaitUntilIdle() {
for d.busy.Get() { for d.isBusy() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
} }
// IsBusy returns the busy status of the display // IsBusy returns the busy status of the display
func (d *Device) IsBusy() bool { func (d *Device) IsBusy() bool {
return d.busy.Get() return d.isBusy()
} }
// ClearBuffer sets the buffer to 0xFF (white) // ClearBuffer sets the buffer to 0xFF (white)