Playing audio information in a Pi Pico and not using a DAC

Playing audio information in a Pi Pico and not using a DAC

antirez 2 days in the past. 1760 views.

The Raspberry Pico is all of the sudden changing into my most popular chip for embedded growth. It is effectively made, sturdy {hardware}, with a ton of options that seem designed with smartness and fervour (the state machines driving the GPIOs are a killer function!). Its fundamental weak point, the dearth of connectivity, is now resolved by the W variant. The information sheet is great and paperwork each side of the chip. Moreover, it's effectively supported by MicroPython (which I’m utilizing loads), and the C SDK atmosphere is respectable, even when filled with ineffective complexities like at present trend calls for: a cmake construct system that in flip generates a Makefile, information to outline this and that (used libraries, debug outputs, …), and usually an enormous overkill for the objective of compiling tiny applications for tiny gadgets. No, it’s worse than that: all this complexity to generate applications for a FIXED {hardware} with a hard and fast set of options (if not for the W / non-W variant). Enough with the rant about how a lot at present software program sucks, nevertheless it should be remembered.

One of the cool issues one needs to do with an MCU like that, is producing some sound. The most evident method to do that is utilizing the built-in PWM function of the chip. The GPIOs might be configured to only alterante between zero and one on the desired frequency, like that:

from machine import Pin, PWM
pwm = PWM(Pin(1))
pwm.freq(400)
pwm.duty_u16(1000)

Assuming you related a piezo to GND and pin 1 of your Pico, you'll hear a sq. wave sound at 400hz of frequency. Now, there are little sounds as horrible to listen to as sq. waves. Maybe we are able to do higher. I’ll skip all of the intermediate steps right here, like producing a sin wave, and instantly bounce to enjoying a wav file. Once you see how to do this, you'll be able to simply generate your individual different waves (sin, noise, envelops for such waveforms and so forth).

Now you're probably asking your self: how can I generate the advanced wave kinds to play a wav file, if the Pico can solely swap the pin excessive or low? A correct non sq. waveform consists of various ranges, so I would wish a DAC! Fortunately we are able to do all this and not using a DAC in any respect, only a single pin of our Pico.

### How advanced sound era works

I don’t wish to cowl an excessive amount of background right here. But all you want to know is that, when you don’t wish to generate a trivial sq. wave, that simply alternates between a minimal and most stage of output, you will want to have intermediate steps, like that:

S0: #
S1: ####
S2: ######
S3: #######
S4: ########

And so forth, the place S0 is the primary pattern, S1, the second pattern, …

Each pattern length is dependent upon the sampling frequency, that's what number of instances each second we alter (when enjoying) or pattern (when recording) the audio wave. This implies that to play a fancy sound, we'd like the flexibility of our Pico pin to output totally different voltages.

There is a trick to do that with the Pico simply utilizing PWM, that's to make use of a sq. wave with a really excessive frequency, however with a special obligation cycle for the totally different voltages we wish to generate. So we set a really very excessive frequency output:

pwm.freq(100000)

Then, if we wish to produce the S0 pattern, we set the obligation cycle (whose worth is between 0 and 65535) to a small worth. If we wish to produce the S1 pattern, we use the next worth, and so forth. In sequence we could wish to do one thing like that:

pwm.duty_u16(3000)   # S0
pwm.duty_u16(12000) # S1
pwm.duty_u16(18000) # S2
pwm.duty_u16(21000) # S3
pwm.duty_u16(24000) # S4

The obligation cycle is how a lot time the pin is about to 1 versus how a lot time the pin is about to 0. An obligation cycle of 65535 means 100% of time pin excessive. 0% means on a regular basis low. All this, whereas preserving the set alternating frequency. So if we zoom like if we now have an oscilloscope, we are able to see what occurs throughout S2 and S3 pattern era:

S2:
######################
#
#
#
#
######################
#
#
#
#

While S3 shall be like:
######################
######################
#
#
#
######################
######################
#
#
#

The pin goes up and down with the identical frequency, however within the case of S3 it stays up extra. This will produce the next common voltage. This permits us to approximate our wave.

### Convert and play a WAV file

In order to play a wav file, we now have to transform it right into a uncooked format that's simple to learn utilizing MicroPython. I downloaded a wav file saying “Oh no!” from SoundCloud. So my conversion will appear to be this:

ffmpeg -i ohno.wav -ar 24000 -acodec pcm_u8 -f u8 output.uncooked

Note that we transformed the file to eight bit audio (256 totally different output ranges per pattern). Anyway our PWM trick is just not going to approximate the totally different ranges so effectively, and we're useful resource constrained. You can strive with 16 bit as effectively, however I bought respectable outcomes like this.

Then, add the output.uncooked file on the machine by way of mpremote:

mpremote cp output.uncooked :

Now write a file referred to as “play.py” or as you want, with this content material:

from machine import Pin, PWM

pwm = PWM(Pin(1))
pwm.freq(100000)

f = open("output.uncooked","rb")
buf = bytearray(4096)
whereas f.readinto(buf) > 0:
    for pattern in buf:
        pwm.duty_u16(pattern<<8)
        x=1
        x=1
        x=1
        x=1
        x=1
f.shut()

What we're doing right here is simply getting the file, 4096 samples per iteration, then “enjoying” it by setting totally different PWM obligation cycles one after the opposite, in keeping with the samples values. The drawback is, in our PCM file we now have 24000 samples per second (see ffmpeg command line). How can ensure that it matches the MicroPython velocity? effectively, certainly it isn't an ideal match, so I added “x=1” statements to delay it a bit to kinda match the pitch that appeared right.

Oh, and if you're questioning what the pattern<<8 factor is, that is simply to rescale a 8 bit pattern to the complete 16 bit precision wanted to set the PWM obligation cycle.

The draw back of all that is that it's going to take your program busy whereas enjoying. I didn’t check it but, however MicroPython helps threading, so to have a thread enjoying the audio may very well be the best way to go.

### Bonus level: sin wave sound era

# Sin wave
wave=[]
wave_samples = 40
pwm.freq(100000)
for i in vary(wave_samples):
    x = i/wave_samples*3.14*2
    dc = int((1+math.sin(x))*65000)
    wave.append(dc)
print(wave)

for i in vary(1000):
    for dc in wave: pwm.duty_u16(dc)

HI-FI News

by way of Hacker News https://ift.tt/baFRzgC

March 8, 2024 at 04:06PM