I’m starting to get more confident with putting components together with the Pico, so without too much research I bought a simple speaker/amplifier breakout board. Still, given how every time I try something simple on the Pico it turns out to involve hours of Googling I assumed that getting a speaker to work would be more fiddly than it should be.
But, au contraire, it turned out to be remarkably easy. Just three cables and not even a dozen lines of code (stolen by Googling, of course…) produced a simple note:
With this code:
from machine import Pin, PWM from utime import sleep SPEAKER_PIN = 21 # create a Pulse Width Modulation Object on this pin speaker = PWM(Pin(SPEAKER_PIN)) # set the duty cycle to be 50% speaker.duty_u16(1000) speaker.freq(1000) # 50% on and off sleep(1) # wait a second speaker.duty_u16(0) # turn off the PWM circuits off with a zero duty cycle speaker.duty_u16(0)
Despite really haven’t done nothing except copy and paste I was proud of the beep that emitted from the small speaker.
The next challenge: to play an audio file, of any format. Back to Google I went, and after some dead ends (due to Micropython changing over the previous five years) I settled on a library called PicoAudioPWM by Daniel Perron.
A bit of MP3 to WAV mangling later, and this code produced a very ropey sound:
from machine import Pin import wave from wavePlayer import wavePlayer try: player = wavePlayer() player.play('clip.wav') player.stop() except Exception as ex: Pin(2, Pin.OUT, Pin.PULL_DOWN) Pin(2, Pin.OUT, Pin.PULL_DOWN)
I changed the output pin from 21 in the simple beep experiment to 2 here, as that’s the default the library uses.
For a reason that I expect is specific to the speaker I had to add a Pin PULL_DOWN after playback was complete otherwise the audio was followed by constant hissing from the speaker, even after the program had stopped running.
The sound quality was pretty awful, but hey-ho: at least I got noise out of the thing.
Now to go and read about what “Pulse Width Modulation” might be…