1- //go:build rp2040 && go1.18
1+ //go:build rp2040
22
33package piolib
44
55import (
6+ "errors"
67 "machine"
78
89 pio "github.com/tinygo-org/pio/rp2-pio"
910)
1011
12+ // I2S is a wrapper around a PIO state machine that implements I2S.
13+ // Currently only supports writing to the I2S peripheral.
1114type I2S struct {
1215 sm pio.StateMachine
1316 offset uint8
1417 writing bool
1518}
1619
20+ // NewI2S creates a new I2S peripheral using the given PIO state machine.
1721func NewI2S (sm pio.StateMachine , data , clockAndNext machine.Pin ) (* I2S , error ) {
1822 sm .TryClaim () // SM should be claimed beforehand, we just guarantee it's claimed.
1923 Pio := sm .PIO ()
@@ -49,10 +53,12 @@ func NewI2S(sm pio.StateMachine, data, clockAndNext machine.Pin) (*I2S, error) {
4953 }
5054 // This enables the state machine. Good practice to not require users to do this
5155 // since they may be confused why nothing is happening.
52- i2s .Paused (false )
56+ i2s .Enable (true )
57+
5358 return i2s , nil
5459}
5560
61+ // SetSampleFrequency sets the sample frequency of the I2S peripheral.
5662func (i2s * I2S ) SetSampleFrequency (freq uint32 ) error {
5763 freq *= 32 // 32 bits per sample
5864 whole , frac , err := pio .ClkDivFromFrequency (freq , machine .CPUFrequency ())
@@ -63,14 +69,26 @@ func (i2s *I2S) SetSampleFrequency(freq uint32) error {
6369 return nil
6470}
6571
72+ // WriteMono writes a mono audio buffer to the I2S peripheral.
6673func (i2s * I2S ) WriteMono (b []uint16 ) (int , error ) {
6774 return i2sWrite (i2s , b )
6875}
6976
77+ // WriteStereo writes a stereo audio buffer to the I2S peripheral.
7078func (i2s * I2S ) WriteStereo (b []uint32 ) (int , error ) {
7179 return i2sWrite (i2s , b )
7280}
7381
82+ // ReadMono reads a mono audio buffer from the I2S peripheral.
83+ func (i2s * I2S ) ReadMono (p []uint16 ) (n int , err error ) {
84+ return 0 , errors .ErrUnsupported
85+ }
86+
87+ // ReadStereo reads a stereo audio buffer from the I2S peripheral.
88+ func (i2s * I2S ) ReadStereo (p []uint32 ) (n int , err error ) {
89+ return 0 , errors .ErrUnsupported
90+ }
91+
7492func i2sWrite [T uint16 | uint32 ](i2s * I2S , b []T ) (int , error ) {
7593 if len (b ) == 0 {
7694 return 0 , nil
@@ -94,10 +112,7 @@ func i2sWrite[T uint16 | uint32](i2s *I2S, b []T) (int, error) {
94112 return len (b ), nil
95113}
96114
97- func (i2s * I2S ) Paused (b bool ) {
98- i2s .sm .SetEnabled (b )
99- }
100-
101- func (i2s * I2S ) Stop () {
102- i2s .writing = false
115+ // Enable enables or disables the I2S peripheral.
116+ func (i2s * I2S ) Enable (enabled bool ) {
117+ i2s .sm .SetEnabled (enabled )
103118}
0 commit comments