Skip to content

Commit 361eff2

Browse files
committed
examples: add simple i2s example to play sine wave
Signed-off-by: deadprogram <[email protected]>
1 parent 27cbe9d commit 361eff2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

rp2-pio/examples/i2s/main.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// this example uses the rp2040 I2S peripheral to play a sine wave.
2+
// It uses a PCM5102A DAC to convert the digital signal to analog.
3+
// The sine wave is played at 44.1 kHz.
4+
// The sine wave is played in blocks of 32 samples.
5+
// The sine wave is played for 500 ms, then paused for 500 ms.
6+
// The sine wave is played indefinitely.
7+
// The sine wave is played on both the left and right channels.
8+
// connect PCM5102A DIN to GPIO2
9+
// connect PCM5102A BCK to GPIO3
10+
// connect PCM5102A LCK to GPIO4
11+
package main
12+
13+
import (
14+
"machine"
15+
"time"
16+
17+
pio "github.com/tinygo-org/pio/rp2-pio"
18+
"github.com/tinygo-org/pio/rp2-pio/piolib"
19+
)
20+
21+
const (
22+
i2sDataPin = machine.GPIO2
23+
i2sClockPin = machine.GPIO3
24+
25+
NUM_SAMPLES = 32
26+
NUM_BLOCKS = 5
27+
)
28+
29+
// sine wave data
30+
var sine []int16 = []int16{
31+
6392, 12539, 18204, 23169, 27244, 30272, 32137, 32767, 32137,
32+
30272, 27244, 23169, 18204, 12539, 6392, 0, -6393, -12540,
33+
-18205, -23170, -27245, -30273, -32138, -32767, -32138, -30273, -27245,
34+
-23170, -18205, -12540, -6393, -1,
35+
}
36+
37+
func main() {
38+
time.Sleep(time.Millisecond * 500)
39+
40+
sm, _ := pio.PIO0.ClaimStateMachine()
41+
i2s, err := piolib.NewI2S(sm, i2sDataPin, i2sClockPin)
42+
if err != nil {
43+
panic(err.Error())
44+
}
45+
46+
i2s.SetSampleFrequency(44100)
47+
48+
data := make([]uint32, NUM_SAMPLES*NUM_BLOCKS)
49+
for i := 0; i < NUM_SAMPLES*NUM_BLOCKS; i++ {
50+
data[i] = uint32(sine[i%NUM_SAMPLES]) | uint32(sine[i%NUM_SAMPLES])<<16
51+
}
52+
53+
// Play the sine wave
54+
for {
55+
for i := 0; i < 50; i++ {
56+
i2s.WriteStereo(data)
57+
}
58+
59+
time.Sleep(time.Millisecond * 500)
60+
}
61+
}

0 commit comments

Comments
 (0)