PWM audio on Pi Zero non working

General project help for Adafruit customers

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Post Reply
User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

PWM audio on Pi Zero non working

Post by Aleph90 »

This might have come up a gazillion times already, but I tried looking at online sources and nothing resolved my issue. I followed LadyAda's tutorial (https://learn.adafruit.com/adding-basic ... -pwm-audio) — I added the `dtoverlay=pwm-2chan,pin=18,func=2,pin2=13,func2=4` line to /boot/config.txt, built a filter, and connected headphones to the jack, but all I'm hearing a bunch of noise. I'm not sure what might be useful for troubleshooting, so here's a bunch of info.
  • The project is a portable console, running RetroPie on a RPi Zero 2W with a 2.8" PiTFT (resistive) over SPI and pushbuttons connected to GPIO for the controls. I have nothing else connected — no HDMI displays, no keyboard. I do everything from my laptop over SSH.
  • The noise I'm hearing is kind of squeaky, it sounds like there is some white noise and on top of that some additional higher-pitch noise.
  • Some of the sound seems to come through, but as a faint background. This includes, for example, clicking sounds on keypresses (SSH) and when I adjust the volume via alsamixer. I tried `aplay`ing something but couldn't hear much.
  • I tried hooking up my headphones directly to GPIO 13 and 18 using alligator clips and it sounds roughly the same. My first thought was the filter is doing nothing and I must have screwed up the wiring, so I tried rebuilding it on a breadboard and I got the same result.
  • Recalling that the PiTFT uses GPIO 18 by default to control the backlight, I also thought of removing its dtoverlay from /boot/config.txt to see what would happen. The high-pitch squeak went away, but I was still left with a lot of white noise.
  • If I sudo raspi-config and then navigate to System Options and then S2 Audio, one of two things happens in an apparently random way. Either I get a message that no sound cards were found, or the config screen disappears for a moment and reappears on the main menu.
  • I also tried using `gpioinfo` from libgpiod to check the status of all pins (since `gpio readall` is not running). The output is kinda obscure since all pins appear as unnamed, but both lines 13 and 18 appear as input and without a "consumer" field, (as does line 45, which I understand from LadyAda's tutorial is supposed to be the default for PWM1). Lines 40, 41, 42 all appear as output but have no consumer. I don't know if this is to be expected.
All of this makes me think there might be a software issue, perhaps a missing configuration or some other software component that's using the same pins at the same time? For reference, here are the contents of my /boot/config.txt (I removed most comments for convenience).

Code: Select all

dtparam=spi=on

dtoverlay=pwm-2chan,pin=18,func=2,pin2=13,func2=4

dtparam=audio=on

[pi4]
# Enable DRM VC4 V3D driver on top of the dispmanx display stack
dtoverlay=vc4-fkms-v3d
max_framebuffers=2

[all]
gpu_mem_256=128
gpu_mem_512=256
gpu_mem_1024=256
#overscan_scale=1
dtoverlay=pitft28-free-ce1,rotate=270,speed=80000000,fps=60
display_rotate=0
hdmi_cvt=320 240 60 1 0 0 0
Any help much appreciated!

User avatar
adafruit_support_mike
 
Posts: 68419
Joined: Thu Feb 11, 2010 2:51 pm

Re: PWM audio on Pi Zero non working

Post by adafruit_support_mike »

Post a photo showing your hardware and connections and we'll take a look. 800x600 images usually work best.

User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

Re: PWM audio on Pi Zero non working

Post by Aleph90 »

adafruit_support_mike wrote: Tue Feb 04, 2025 10:28 pm Post a photo showing your hardware and connections and we'll take a look. 800x600 images usually work best.
Thanks Mike! I actually spotted what I think is the main problem: The guidelines I was using work for the Pi Zero, but I have a Zero 2W, which uses a different processor and can re-route audio as PWM on different pins than the original — either 12 and 13 or 18 and 19, while I was using 13 and 18. I have replaced the line `dtoverlay=pwm-2chan,pin=18,func=2,pin2=13,func2=4` in boot config with `gpio=12,13,a5`, `audio_pwm_mode=2`, and `dtoverlay=audremap,pins_12_13`. Before changing any permanent connections, I tested the new settings by connecting one channel of my headphones to pin 13 and there is still the same nasty background, but I am receiving audio at least. The funny thing is, if I change the volume through alsamixer, the actual sound changes volume accordingly, but the noise remains constant. I will now do the due changes to wiring and re-test.

Let me still share pictures of my setup — hopefully it's not too messy. Here are all the components involved:
components.jpg
components.jpg (166.94 KiB) Viewed 48 times
Left-right, top-bottom, you can see a PowerBoost 1000, a battery, the Pi, a PAM8302 amp, the filter I put together, and the "breakout" I made. The connections on the audio amp are not too visible, but they are as follows. Ground is connected to the PowerBoost ground (blue wire) and to the 3-pin JST connector. Vin is connected to PowerBoost 5V (red wire). A+ and A- go to the JST (red and blue, resp.). + and - are connected to loose red and blue wires, resp., which I will eventually connect to a speaker; they go under the battery in this picture because I just needed to block them out of the way.

Here's a closeup of the breakout:
breakout.jpg
breakout.jpg (159.78 KiB) Viewed 48 times
It's a 20x2 female pin header with wires attached to the pins I need for my projects. The pins for power, ground, buttons, and SPI connections are then connected to a row of pins soldered to a proto board with additional pin headers so I can easily connect the other components. Pins 13 and 18 are connected to the green and yellow wires (respectively) attached to the JST. Those break out the audio pins (I am going to move the yellow wire from 18 to 12). The loose red wire is a later addition I made, it's for SPI and doesn't have much to do with audio.

Once connected, the setup looks like this:
fully_wired.jpg
fully_wired.jpg (173.06 KiB) Viewed 48 times
I seem to be having trouble uploading more pictures, so I'll post close-ups on the filter in a separate post.

User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

Re: PWM audio on Pi Zero non working

Post by Aleph90 »

...and here's the filter. Please note the picture of the back is mirrored — I figured this might make it easier to understand the connections.
filter.jpg
filter.jpg (256.75 KiB) Viewed 47 times

User avatar
adafruit_support_mike
 
Posts: 68419
Joined: Thu Feb 11, 2010 2:51 pm

Re: PWM audio on Pi Zero non working

Post by adafruit_support_mike »

Nice work!

I'm glad to hear you solved the problem of routing the audio signals.. there's an inevitable conflict of interests between maintaining compatibility with older versions of a platform and letting newer versions do something else. Both have their advantages and costs. The RasPi Foundation leans toward doing the new thing, which can make porting ideas from one board to another tricky.

The noise you're hearing is probably switching noise from one of the voltage regulators. The fact that the RasPi and PAM8302 get power from the PowerBoost means the signals through the A+ and A- lines see an additional current path through the GND line. Switching converters are notorious for injecting noise into signals that way.

User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

Re: PWM audio on Pi Zero non working

Post by Aleph90 »

adafruit_support_mike wrote: Sun Feb 09, 2025 8:20 pm Nice work!
Really? It looks good? :D
adafruit_support_mike wrote: Sun Feb 09, 2025 8:20 pm I'm glad to hear you solved the problem of routing the audio signals..
Well, solved to an extent. I can hear sound now, but mainly from the jack port/headphones, and the noise is still there — more on that below.
adafruit_support_mike wrote: Sun Feb 09, 2025 8:20 pm The noise you're hearing is probably switching noise from one of the voltage regulators. The fact that the RasPi and PAM8302 get power from the PowerBoost means the signals through the A+ and A- lines see an additional current path through the GND line. Switching converters are notorious for injecting noise into signals that way.
I'm looking for examples of switching noise to know what it sounds like; little luck so far. Is there another way to test if it's that? I don't have an oscilloscope unfortunately... If it's of any relevance, I did most of my testing through jack/headphones, so no amp. I also did some testing without the PowerBoost, feeding the Pi from a wall through USB (see below).

It's hard to describe the sound I'm hearing; it's like a fixed-intensity sound that swings between maybe two or three different pitches — it doesn't gradually transition from one to another but rather jumps at irregular intervals.

The update is that I have now moved the yellow wire from GPIO 18 to GPIO 12 and attached a speaker to the amp (8R, .5W). I am getting sound, clear and decent without distortions, but the noise is still very much present, and the speaker output is rather faint, perhaps even quieter than the headphones. I've also seen some weird behaviour on the display — some flickering and other distortions that seem correlated to sound. I can say more on this if it's relevant, but I'm thinking it might have to do with the length of the wires on the SPI bus (15cm, or 6in).

So, I thought to try and further isolate the problem, by testing the audio filter with minimal connections and a breadboard as follows.
breadboard.jpg
breadboard.jpg (177.4 KiB) Viewed 43 times
In case the picture isn't clear enough (sorry!), the purple wire connects physical pin 6 (GND) to the breadboard ground; black and white are GPIO 12 and 13, connected on the breadboard to green and yellow, respectively; green and yellow are then input to the filter; orange connects breadboard ground to filter ground.
I then powered the Pi from micro USB and, well, same result. Screeching noise all over, a little erratic in intensity, as it will sometime lower or disappear if I play audio and then gradually come back. While I was as it, I also tried "listening" to all of the GPIOs by connecting the white wire to each of them (and disconnecting the black) — this means the signal was filtered before reaching the headphones. I caught the exact same noise, only much louder, on GPIOs 8, 10, and 11, which are the SPI pins (clock, chip enable, and COPI, not in order); I also heard it on the 5V power pins but somewhat "muffled" and with additional static. On most other pins I heard silence or static, which I suppose makes sense, except for GPIO 25 (display data/command), which had a rhythmic clicking sound, which again makes sense.

Does this behaviour fit the switching noise theory? I've only ever read about it just now, but from my understanding it kinda makes sense. The point would be (please correct me if I'm wrong) that the power input is not at a constant 5V, but rather oscillates by a fraction of a mV, and if this voltage is the baseline for setting pins to low or high, whatever output appears on the GPIO would be distorted by this oscillation. But then should I expect to hear the same exact distortion whether I'm powering the Pi from the PowerBoost or a wall power supply through USB? And if COPI, SCL, and CE0 are oscillating, shouldn't I hear the noise at a fraction of the volume in that case? I mean, the clock is up half the time and down the other half, switching at a rate way above audible frequency, so what I'd expect to hear there is the same as on the 5V pin but at half the volume.

At any rate, assuming it is switching noise, is there a tutorial or guide to getting rid of it? It really is rather prominent... And are there any obvious wiring issues that are killing the output on my speaker? (And sorry for writing too much...)

User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

Re: PWM audio on Pi Zero non working

Post by Aleph90 »

Quick addition: Following the ideas above, I've also tried "listening" to the PowerBoost output, touching its 5V output with the yellow wire (filter input) and ground with the orange wire (filter ground). No sound at all. I don't know if it matters that the Pi wasn't connected — does this mean the screeching noise is not caused by the PowerBoost's voltage regulators?

User avatar
adafruit_support_mike
 
Posts: 68419
Joined: Thu Feb 11, 2010 2:51 pm

Re: PWM audio on Pi Zero non working

Post by adafruit_support_mike »

Aleph90 wrote: Mon Feb 10, 2025 1:14 am Really? It looks good? :D
Sure: it's orderly and well organized.

There are people who take protoboard construction into the realm of circuit sculpture, but the gap between their work and the boards above is mostly wire forming. With some simple tools and jigs you could do show pieces too. Doing pretty takes 3 to 4 times as long as doing functional, and won't always be worth the effort, but sometimes it can be fun.
Aleph90 wrote: Mon Feb 10, 2025 1:14 am I'm looking for examples of switching noise to know what it sounds like; little luck so far. Is there another way to test if it's that?
In this case, give the RasPi a completely different power supply. The only wires that connect to the PAM8302 should be the A+ and A- lines.
Aleph90 wrote: Mon Feb 10, 2025 1:14 am It's hard to describe the sound I'm hearing; it's like a fixed-intensity sound that swings between maybe two or three different pitches — it doesn't gradually transition from one to another but rather jumps at irregular intervals.
That's consistent with switching noise, and sounds more like the RasPi than the PowerBoost.

Switching regulators basically work by PWM: they connect input power part of the time, and output power the rest of the time. That gives the illusion of changing the current: 150mA 66% of the time averages to 100mA, while 150mA 33% of the time averages to 50mA. If you send that current through an inductor it can change the voltage to balance the apparent change in current: you get what looks like 100mA at N Volts going in, and 50mA at 2N Volts coming out.

More advanced switching converters change their duty cycle and frequency to change the amount of power that flows through them.

The RasPi uses a technique called 'clock switching' to balance performance versus power consumption.. slowing the clock down to save power when the system is idle, then speeding it up to keep the system responsive when it's busy. The RasPi's onboard regulators will adjust to the new load with changes in frequency and duty cycle.
Aleph90 wrote: Mon Feb 10, 2025 1:14 am I've also seen some weird behaviour on the display — some flickering and other distortions that seem correlated to sound.
That could mean the audio amp is drawing enough current to leave the RasPi short on power. That's not too surprising.. speakers are current-hungry beasts.

Moving the RasPi temporarily to a separate power supply should also make that go away.

You might also try changing the scale of your filter: the frequency where a filter starts to attenuate signals is based on the product of the resistor and capcitor values. All resistor-capacitor combinations with the same product will have the same frequency response, but more current will flow through the one with lower resistance.

The same thing applies to voltage dividers: a 1k-1k divider will carry a hundred times as much current as a 100k-100k, but they'll both have the same voltage at their center. A filter is just a voltage divider that cares about frequency.

If you have a ground loop, reducing the current through the A+/A- lines should have an effect on it. Try scaling your resistors up 10x and your capacitors down 10x and see if it makes any difference. You'll get much less volume driving headphones directly from the filter, but the PAM8302 uses very little input current.

User avatar
Aleph90
 
Posts: 34
Joined: Thu Jun 17, 2021 9:52 am

Re: PWM audio on Pi Zero non working

Post by Aleph90 »

Thanks again Mike!
adafruit_support_mike wrote: Wed Feb 12, 2025 2:35 am There are people who take protoboard construction into the realm of circuit sculpture, but the gap between their work and the boards above is mostly wire forming. With some simple tools and jigs you could do show pieces too. Doing pretty takes 3 to 4 times as long as doing functional, and won't always be worth the effort, but sometimes it can be fun.
The plan is actually to start designing some custom PCBs for this project once I have a satisfying prototype running with all the features I want. What you're not seeing in the pictures I've shared so far is the jungle of wires connecting the breakout to the display and buttons. But I think I know what you're talking about and the idea is actually interesting...

That aside, I think I understand the switching business better now, and what you say partly confirms what I thought, particularly the fact that as far as the Pi is concerned, "high" doesn't really mean a clean constant 3.3 or 5V, but some oscillating voltage that "looks" like it. I still have some unclear points though.
  1. If that's the case, the PWM pins will always be outputting the switching noise on top of the intended sound, so even if I feed the PAM8302 from a separate source won't the noise be amplified alongside everything else?
  2. Much of the testing I've done did not involve the PAM8302 at all. The jack only connects to the PWMs and ground, and I don't imagine it would make much sense to ground the jack on a separate power supply. It seems to me that the idea of separating power supplies only has a hope to work with the amplifier, not so much the jack, or am I missing something?
  3. When you say "Moving the RasPi temporarily to a separate power supply", what do you mean "temporarily"? Are you suggesting this just as a strategy for testing to see if the noise goes away?
  4. Noise aside, I still haven't been able to get audible sound out of the amplifier. What's coming out seems comparable if not even quieter than what I'm getting from my headphones through the jack. Could this have something to do with differential input? I seem to understand that the PAM8302 takes in the difference of what's on A+ and A- and amplifies that. Is that right? Could I be getting outputs from the PWM's that are so similar that the difference is so small that even the amplified signal is still weak?
  5. When you said "You'll get much less volume driving headphones directly from the filter, but the PAM8302 uses very little input current", does that mean that the volume I get on my headphones depends on the current being put out of the filter, while the amplifier only looks at the voltages?
  6. If the Pi is powered from the PowerBoost via the 5V power pin, shouldn't the PowerBoost control the voltage on it rather than the Pi, and keep it at a fixed 5V? Of course I imagine the PowerBoost will have its own switching regulators so there may still be noise coming from that, but then I'd expect the noise to sound different depending on the power source, while in my tests it really sounded the same using a wall adapter as it did with the PowerBoost.
  7. Why did LadyAda's solution work on the original Pi Zero? The diagram and values for the components of the filter were taken straight from some other Pi model (Pi B) that has an integrated jack taking its input straight from the processor's PWM pins, so how does that Pi work around the switching noise? Or any of all the other Pi's that have integrated jacks for that matter? Am I to understand that some of the older Pi models aren't using switch regulators? I saw the audio circuit schematic on the Pi 4 and they're a little more complex, but mainly it's using a NC7WZ16 buffer. Is that what's getting rid of the noise?
Ok, sorry, some of that that is probably leaving Adafruit ground and steering towards Raspberry Pi questions. I'm not so sure about the idea of splitting power sources as a long-term solution: that sounds to me like I would end up needing two batteries (i.e. weight) and two power supply circuits, which in turn means I won't be able to charge them at the same time unless I use two cables connected to separate wall adapters. Sounds impractical for a portable project. I will try playing around with the values of resistors and capacitors, but I'm not excited about losing volume on the audio jack. In fact, I do have a preference of headphones over speaker — the speaker is kind of a plus to make the project more complete, but its audio quality is what it is and I expect using headphones more often regardless.

I'm thinking if there may be more radically different solutions I might look toward. I'm thinking maybe tapping into the HDMI output to get sound from there, or perhaps get a bluetooth module to run the jack and speakers. Feels a bit like overkill to use bluetooth to communicate with a device mere centimetres away, but hey. I do have a CSR8645 I was expecting to use for a different project, plus if I go the bluetooth route I might be able to allow myself to switch between wired headphones via the jack and wireless ones.

User avatar
adafruit_support_mike
 
Posts: 68419
Joined: Thu Feb 11, 2010 2:51 pm

Re: PWM audio on Pi Zero non working

Post by adafruit_support_mike »

Aleph90 wrote: Thu Feb 13, 2025 1:35 am If that's the case, the PWM pins will always be outputting the switching noise on top of the intended sound, so even if I feed the PAM8302 from a separate source won't the noise be amplified alongside everything else?
The noise will be there, but it won't matter. It will be what's called 'common mode' noise on a 'differential' signal.

Voltage is kind of like distance: you have to measure it between two points. In most cases we declare GND to be the 0V reference from which all other voltages in a circuit are measured. Functionally though, you can measure any signal relative to any other one.

That turns out to be useful when you have two signals with equal voltage but opposite polarity.. one goes up when the other goes down, and they always remain symmetric around some middle voltage. We can break that down mathematically as:

line1 = positive-signal + offset
line2 = negative-signal + offset

Since the offset appears in both parts we call it the 'common mode' part of the signal, with the other parts being the 'differential' signal.

Using one line as the reference for the other gives us:

signal-of-interest == line1 - line2 == ( positive-signal + offset ) - ( negative-signal + offset )

The common mode offset gets both added and subtracted, leaving only the difference between the differential parts of the signal. Moving that idea to hardware, the circuit receiving a differential signal can't even see the common mode offset.

If we extend that idea by adding noise we get:

line1 = positive-signal + offset + noise
line2 = negative-signal + offset + noise

As long as we have the same noise on both lines, that noise is part of the common mode signal. A receiver can't even see it unless you have a third connection to some other shared reference voltage (the ground loop).
Aleph90 wrote: Thu Feb 13, 2025 1:35 am Much of the testing I've done did not involve the PAM8302 at all. The jack only connects to the PWMs and ground, and I don't imagine it would make much sense to ground the jack on a separate power supply. It seems to me that the idea of separating power supplies only has a hope to work with the amplifier, not so much the jack, or am I missing something?
Based on the info above, the jack should only have the A+ and A- signals. Adding a GND connection is what makes any common mode noise detectable.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am When you say "Moving the RasPi temporarily to a separate power supply", what do you mean "temporarily"? Are you suggesting this just as a strategy for testing to see if the noise goes away?
Yep. The first rule of troubleshooting is "don't believe anything you haven't confirmed by physical measurement."

We rely on a lot of assumptions when thinking about circuits, some of which are embarrassingly easy to get wrong.. I've been caught by "of course the power is connected" more times than I'd like to admit. In many cases, it's easier to test your basic assumptions by changing the design rules for a given project. The change doesn't have to be permanent, just long enough to confirm your assumptions or identify a problem. But don't be afraid to change things long enough to get information you need.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am I seem to understand that the PAM8302 takes in the difference of what's on A+ and A- and amplifies that. Is that right?
Exactly, yes.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am Could I be getting outputs from the PWM's that are so similar that the difference is so small that even the amplified signal is still weak?
That's possible. Another possibility is that you have a ground loop making the noise on the A+ and A- lines visible, and the noise is larger than the audio signal. This is one of the reasons electronics types like oscilloscopes so much.. being able to see what the signals are actually doing makes diagnosis a lot easier.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am When you said "You'll get much less volume driving headphones directly from the filter, but the PAM8302 uses very little input current", does that mean that the volume I get on my headphones depends on the current being put out of the filter, while the amplifier only looks at the voltages?
Yes.

There are two kinds of amplifiers: preamps and power amps. A preamplifier converts a small change of input voltage (say +/-1mV) to a large change of output voltage (+/-1V) as accurately as possible. A power amplifier converts a signal with very little current (+/-1V @ 1mA) to one with a lot of current (+/-1mV @ 1A).

Amplifiers are powered circuits, so you have to choose between spending energy to get more voltage or spending energy to get more current. Trying to do both at the same time is less effective than doing one or the other really well, then putting 'more voltage' and 'more current' in series.

When you drive the headphones directly, all the current the speakers get has to come from the input signal. The PAM8302 is a power amp with a separate power connection though, so it doesn't need to pull current from the input signal. In fact, it's easier to get accurate and responsive input if the input stage draws as little current as possible.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am If the Pi is powered from the PowerBoost via the 5V power pin, shouldn't the PowerBoost control the voltage on it rather than the Pi, and keep it at a fixed 5V? Of course I imagine the PowerBoost will have its own switching regulators so there may still be noise coming from that, but then I'd expect the noise to sound different depending on the power source, while in my tests it really sounded the same using a wall adapter as it did with the PowerBoost.
In theory the PowerBoost should send the RasPi 5V, and the RasPi's onboard voltage regulators will add another layer of control to the voltage the CPU sees.

In reality there are two problems: the first is that regulators reduce noise but can't remove it completely. The second is that you can't regulate what isn't there.

Noise reduction involves noticing a change, deciding what to do about it, and enacting the change. Each of those steps takes time, so there's always some lag between the input and the response. That means there's a category of changes that happen too fast for the regulator to correct. That's compounded by the simplest kind of control systems whose correction is proportional to the error they see.. perfect correction would mean they wouldn't see any error to correct.

(there are better options, but they're more complicated, more expensive, use more parts, and still aren't perfect)

That kind of correction applies to voltage spikes, but can't do anything about voltage dips. There's nothing a regulator can do about a load that wants more current than the supply can deliver.

Switching regulators like the PowerBoost use PWM, so their output is full of spikes and dips. The RasPi uses PWM to generate audio output, and the PAM8302 is also a PWM device. Combining PWM systems creates all sorts of problems when the pulses line up with each other, so there are plenty of ways to generate detectable noise.
Aleph90 wrote: Thu Feb 13, 2025 1:35 am Why did LadyAda's solution work on the original Pi Zero?
The circuit in the tutorial demonstrates the basic idea but requires the right operating conditions. The RasPi's GPIO pins can't supply much current, so you need high impedance headphones or powered speakers. Most of our audio demos use USB powered speakers, which would sidestep the problem of noise from a shared power supply.

Post Reply
Please be positive and constructive with your questions and comments.

Return to “General Project help”