Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Higher-Resolution Higher-Frequency PWM on standard microcontroller

Status
Not open for further replies.

dougy83

Well-Known Member
Most Helpful Member
Hi,

As everyone knows, a cheap DAC can be created by filtering PWM using a RC - or other - filter. The higher the PWM freq, the less time it takes for the DAC output to settle as the time constant of the filter can be reduced. It's easier to filter out the carrier if it's far away from the analogue signal we're trying to represent.

e.g. if we wanted to produce an 8-bit PCM audio signal using a 4MHz PIC STD PWM module, the PWM freq would be 4M/4/256 = 3.9KHz, which is right in the audio spectrum and a bit tough to remove (not to mention that it gives us an awfully low sampling rate for audio). If we use either of the following proposed methods, the PWM frequency is increased to 62.5kHz, which is easier to filter out (although the sampling rate will be 3.9KHz). Using a 20MHz osc increases the above rates to 19.5kHz (standard) and 312.5kHz (proposed) respectively, the latter being much easier to filter out from our audio frequency spectrum (e.g. 0-8kHz).

So why aren't the following two methods employed to provide a PWM having the same or higher resolution and frequency? What's wrong with them?

A) Dual PWM channels: most significant channel summed with attenuated less significant channel. The configuration shown in the attached circuit gives 8-bit resolution but at 16 times the frequency of the standard single channel. With a 1% error in both resistors, the worst case error is ~0.31 LSb. It suffers from needing more hardware (attenuator & perhaps buffer) and having a higher output impedance.

B) "Submodulated" PWM. A single PWM channel in the normal configuration is used, but its duty cycle is potentially updated every output cycle. e.g. using 4-bit PWM with 4-bit subsampling, the value 0xE4 might be represented by the PWM sequence (shown as 4-bit PWM hex values): E, E, E, F, E, E, E, F, E, E, E, F, E, E, E, F. The main carrier frequency will count for most of the unwanted energy, but there will also be a small amount at the sub carrier frequency (in this case it's 1/4 of the main frequency).


I actually notice that the (A) is used, see https://www.electro-tech-online.com/custompdfs/2012/08/article_pcm15_20040813.pdf, though that is the only article I found; perhaps I didn't look hard enough.
 
A) Is a nice idea but means you need to have a PIC with dual PWM channels. That means a more expensive and larger PIC, where you could probably use 20MHz or 40MHzPLL clock. It also means you can't do stereo as both PWMs are used to make mono.

B) I think is faulty in theory and will only produce an accruate output when the input freq is very low and averaged by severe enough filtering in the output. In other words it's distortion per PWM cycle will be very high and the severe filtering needed will outweigh any benefits from a higher freq PWM.

C) If you must use a low cost PIC that is limited to 4MHz, since you have only 8bit sound you could use 8 digital outputs into a cheap R2R resistor network. This will give you full 8bit resolution at a much higher quality than PWM as you need much less filtering. It also allows any samplerate you choose, not limited to the PWM module.

D) You could consider a high frequency 1bit Sigma Delta converter, this can easily give you 8bit resolution and th 8bit math is very fast meaning you could run a samplerate 100kHz or higher. However Sigma Delta means you can't easily get the full range output so your 8bit output needs to be scaled between say 25%-75% of Vdd.

E) You could use a 1bit output like my BTc PICsound system that digitally models the 8bit sound to match the behaviour of a simple RC filter. This should be even faster than Delta Sigma but will still have a high distortion per bit.
 
Last edited:
Hi,

Employed in what? Who knows if they are being used in some product somewhere?

The second one i call "dithering" because it is basically switching between two different integer values to produce a third in between value. Thus equal time hex 4 and hex 5 produce the value 4.5 and 4,4,4,5 produces 4.25 etc. That idea is used in lower resolution graphics too and they refer to that as dithering.

There is also analog phase modulation of two independent PWM signals, but the two PWM's have to come from separate chips. Modulating the phase between them produces a single PWM signal, but to get analog resolution the two chips have to be phase modulated using an analog method. Probably not what you are looking for here but i thought i would mention it.

So i guess you are trying to reproduce audio then, or a slower signal?
 
Hi Roman,

Thanks for the comments.

>> A) Is a nice idea but means you need to have a PIC with dual PWM channels. That means a more expensive and larger PIC, where you could probably use 20MHz or 40MHzPLL clock. It also means you can't do stereo as both PWMs are used to make mono.
True. The more capable PICs have PWM timebase of FOSC rather than FOSC/4 as well. You can still apply the dual channel method to increase the frequency and relax the filter requirements and improve the quality, or even to relax the FOSC freq (to decrease the current draw).

I don't think stereo capabilities are of import generally with such limited resource microcontrollers.

>> B) I think is faulty in theory and will only produce an accruate output when the input freq is very low and averaged by severe enough filtering in the output. In other words it's distortion per PWM cycle will be very high and the severe filtering needed will outweigh any benefits from a higher freq PWM.
I don't believe you. ;) I will run a sim to see what the spectrum is like. The carrier freq will be higher and will relax the filt. requirements.

The sample rate is not increased, just the carrier freq; e.g. 8bit/8kHz samples will still be represented by 125us length samples. During this time there will be 16x as many transitions is all..

Yes, Mr Al, it is dithering. When I did a search on dither PWM, there are quite a few hits!

>> C) If you must use a low cost PIC that is limited to 4MHz, since you have only 8bit sound you could use 8 digital outputs into a cheap R2R resistor network. This will give you full 8bit resolution at a much higher quality than PWM as you need much less filtering. It also allows any samplerate you choose, not limited to the PWM module.
Yes, true, if there's enough pins that will provide quieter signal. If the PWM is fed into the LSb of the R-2R DAC, you could get even more resolution from this approach...

>> D) You could consider a high frequency 1bit Sigma Delta converter, this can easily give you 8bit resolution and th 8bit math is very fast meaning you could run a samplerate 100kHz or higher. However Sigma Delta means you can't easily get the full range output so your 8bit output needs to be scaled between say 25%-75% of Vdd.
>> E) You could use a 1bit output like my BTc PICsound system that digitally models the 8bit sound to match the behaviour of a simple RC filter. This should be even faster than Delta Sigma but will still have a high distortion per bit.
Those methods are similar enough, but use more storage bandwidth.. e.g. 8 bits of PCM stores 256 levels, whereas for 256 levels in S-D or BTc you need 256 bits.

>> Employed in what? Who knows if they are being used in some product somewhere?
No idea. I guess I meant, why isn't it an encouraged method?

>> So i guess you are trying to reproduce audio then, or a slower signal?
I was just thinking about how to simply create an audio or reference signal without adding too much hardware and getting a much better resolution with a lower settling time (or less noise/ripple) than using standard PWM.
 
Last edited:
Ok, the dithered frequency response is shown for a DC signal of 0x61 -- the '1' in the LSN will have the lowest frequency components. The signal is DC (f = 0) -- all the rest is noise.

The standard PWM has about 2dB more signal at DC, and 0.27dB less signal at the first peak -- f=0.0039 for standard and f=0.0667 for dithered (so the lowest noise peak for dithered is 17x higher than standard -- this is much easier to filter out).

The dithered response sits around the -37dB (equivalent to 8bit quantisation noise), but the standard pwm response has plenty of noise in the low freq region.

Code:
% create a pwm signal to represent 0x61 (97 decimal) - this will have the
% lowest frequency due to LSN = 1
v = 97;
cycles = 3000;

% standard pwm
sp = [ones(1, v) zeros(1, 255 - v)];
sp = reshape(sp' * ones(1, cycles), 1, length(sp) * cycles) - 0.5;

max_sp = max(sp);

subplot(121)
[f,r] = getfft(1,sp);
sp_r_max = max(abs(r));
plot(f,20*log10(abs(r)/sp_r_max));
axis([-.1 0.5 -50 10])
title('Standard 8-bit PWM freq response')
ylabel('Response (dB)')
xlabel('Freq (norm)')

% dithered pwm
vh = floor(v / 16);

lv = [ones(1, vh) zeros(1, 15 - vh)];
hv = [ones(1, (vh+1)) zeros(1, 15 - (vh+1))];

dp = [lv lv lv lv lv lv lv lv lv lv lv lv lv lv lv lv hv];
dp = reshape(dp' * ones(1, cycles), 1, length(dp) * cycles) - 0.5;

subplot(122)
[f,r] = getfft(1,dp);
plot(f,20*log10(abs(r)/sp_r_max));      % normalise to max of standard PWM
axis([-.1 0.5 -50 10])
title('Dithered 4x4-bit PWM freq response');
ylabel('Response (dB)')
xlabel('Freq (norm)')
 
>> So i guess you are trying to reproduce audio then, or a slower signal?
I was just thinking about how to simply create an audio or reference signal without adding too much hardware and getting a much better resolution with a lower settling time (or less noise/ripple) than using standard PWM.

Oh yes ok. Well, the audio signal would take more effort than a reference signal. A reference signal would be easier to do because it would just be a sine wave (i guess that's what you meant). A pure sine wave would be easier to do than an audio signal even if it just had to repeat over and over again.
With the sine wave you might be able to fine tune the levels to give a higher bit perception because the upper part of the sine is more important than the lower levels of the sine. Higher resolution near the upper part and lower res near the lower parts would probably give better results than with medium res over the whole height.
 
A reference signal would be easier to do because it would just be a sine wave (i guess that's what you meant).
Yes, with a sine wave you would know which harmonics would need filtering out so you may have more control that way. I was thinking of a reference voltage like e.g. to control a variable voltage regulator output; sometimes it's useful to be able to get 16-bit resolution without having to put a multiple second RC filter on to reduce the noise/ripple

With the sine wave you might be able to fine tune the levels to give a higher bit perception because the upper part of the sine is more important than the lower levels of the sine.
I'm not following - how would you change the resolution? The PWM output is linear by its nature...??


Higher resolution near the upper part and lower res near the lower parts would probably give better results than with medium res over the whole height.
Again, I'm not sure how the change in resolution is accomplished, but certainly expanding does increase the dynamic range, and if the signal is sampled at the correct time (ie nonuniform sample period) the signal will be improved.
 
Yes, with a sine wave you would know which harmonics would need filtering out so you may have more control that way. I was thinking of a reference voltage like e.g. to control a variable voltage regulator output; sometimes it's useful to be able to get 16-bit resolution without having to put a multiple second RC filter on to reduce the noise/ripple

I'm not following - how would you change the resolution? The PWM output is linear by its nature...??


Again, I'm not sure how the change in resolution is accomplished, but certainly expanding does increase the dynamic range, and if the signal is sampled at the correct time (ie nonuniform sample period) the signal will be improved.

Hi again,

Well normally we think of the entire dynamic range as being weighted the same...ie 1bit change near the low end of the entire range might mean 5mv and 1bit change near the top end of the range usually still means 5mv, but since the sine wave harmonic content is more sensitive for higher level parts of the sine than lower parts of the sine we might gain some distortion points simply by weighing the bits differently where 1bit near the top might mean 2.5mv instead of 5mv. 2.5mv near the top could introduce the same distortion as a 5mv change near the bottom. So in other words it would be a non linear weighing.
You were using resistors to change the 'fine' resolution so this came to mind. Might be more applicable where there are more bit channels to begin with.
 
Ok, that makes sense, I was on some other wavelength. One range per PWM channel; sounds good
 
...
I don't believe you. ;) I will run a sim to see what the spectrum is like. The carrier freq will be higher and will relax the filt. requirements.

Feel free! :)

Dithering a PWM to get higher resolution is not a new concept, just be aware that if you are dithering 16 pulses of 4bit PWM you make one complete "sample" have the same total period as one complete sample of 8bit PWM.

Your original question was regarding reproducing HIGHER frequencies using 1Mhz PWM clocking and 8bit samples. Your proposed "dithering 16 sets of 4bit PWM" still takes the same total time to reproduce ONE 8bit sample, which is why I said "I think this is faulty in theory" as since both systems take the same total time per sample both will suffer the same top frequency limit. :)

...
Those methods are similar enough, but use more storage bandwidth.. e.g. 8 bits of PCM stores 256 levels, whereas for 256 levels in S-D or BTc you need 256 bits.

No the DeltaSigma system is 8bit, with an 8bit sample at equal storage as 8bit PWM and played back at equal quality of resolution. My BTc system gives an 8:1 data compression as each 8bit sample is reduced to a 1bit sample for playback (with obvious lowering of the sound quality).

The big benefit of 8bit DS is that at a rate of 100kbit/second the average output frequency will approach 50kHz and the 8bit sample rate can be anything you like (like 10kHz), while with your 8bit-4bit dithering system the freq is 25kHz and the sample rate is fixed at a lowly (25/16) = 1.5kHz.
 
Last edited:
If you can generate evenly distributed random numbers very fast, you can get fast "PWM" of any resolution with all the "switching noise" spread to a wide frequency range (no high-energy peaks in the spectrum):

Code:
uint16_t random, duty;

while(1){
    random = generate_random();

    if (random < duty) {
        output_low();
    } else {
        output_high();
    }
}

This way the resolution is completely separated from the frequency. I've been able to generate 10bit signals at ~200 kHz (output update frequency) using Atmel XMega microcontroller.
 
Last edited:
Hi,

misterT:
That's a good idea except when you are expecting a certain noise frequency.

MrRB:
Are you also talking about when you have more than one bit channel? I think it is faster because you can work with lower resolution PWM while working with higher res analog. So the tradeoff is extra channels (pins).
 
To MisterT; Great idea using the random PWM. I see a potential problem with pure random numbers producing audio artifacts, as if the PWM value is near the middle, and the RNG rolls a lot of low values consecutively, you get a long low output.

One of the benefits of DS in comparison is that the hi-lo times are known and based on the PWM value, so if the PWM is kept within the 25-75% zone the total hi-lo period won't exceed a worst case of HHHL or LLLH, giving a lowest freq of bitrate /4.

But, maybe you could use a specifically tuned set of RNG values that has no consecutive hi and low data. It could even be possible to code a psuedo RNG that outpouts successive hi and lo "random" bytes?

To MrAL; I'm not sure what part of my post your question was addressing, sorry. :) If using the PIC PWM module it's limited to 1 or 2 channels, and will be faster bitrate than DS but require significant processor time to keep monitoring and changing the PWM register value.

Besides speed the DS system is good because it is very flexible, there is no specific limit on bitrate or samplerate or resolution. With a cheap 8bit PIC 16F etc you can easily make a 32bit DS system which is really a single pin DAC output with a resolution in the billions.
 
Feel free! :)
I did, spectrum plots attached to above post.
Dithering a PWM to get higher resolution is not a new concept, just be aware that if you are dithering 16 pulses of 4bit PWM you make one complete "sample" have the same total period as one complete sample of 8bit PWM.
Yes, you are quite right that dithering is not a new concept - I just couldn't find any references to it (as I wasn't searching with the correct terms obviously). I'm still curious why it's not used though.

I am well aware that 16x16 is 256 and that 4bits x 4bits --> 8bits, as can be seen in my first post. As the spectrum plots show, the 'carrier' frequency peak is around 16 times higher for the dithered PWM over the standard PWM. The increased PWM frequency (and increased first peak in the output spectrum) is easier to remove using a basic filter.

The BTc program produces a output with a lot of noise and distortion even with 1.6bit, 64000Hz, BTc16/32/64 fineness.

Your proposed "dithering 16 sets of 4bit PWM" still takes the same total time to reproduce ONE 8bit sample, which is why I said "I think this is faulty in theory" as since both systems take the same total time per sample both will suffer the same top frequency limit. :)
There was obviously a misunderstanding; I stated explicitly in my first post that the sampling rate is not changed.

If you can generate evenly distributed random numbers very fast, you can get fast "PWM" of any resolution with all the "switching noise" spread to a wide frequency range (no high-energy peaks in the spectrum):
Your method is very good. A random bitstream with a '1' density equal to the duty cycle would be one of the best ways to produce the output due to the potentially high output toggle rate. A maximally-changing bitstream with the correct '1' density might be even better (due to potentially even higher output toggle rate).

As I understand DS (which is not well), at the start of every audio sample (e.g. every 125us @ 8ksps) the output would rapidly approach the sample value, and then once there would stop moving (as the error is now ~0). So there'd be a fast change at the start edge of every audio sample. This would result in a higher energy at the sample rate than there would be from the other [pwm, random] methods, which have a slower change in output level.
 
Last edited:
...
As I understand DS (which is not well), at the start of every audio sample (e.g. every 125us @ 8ksps) the output would rapidly approach the sample value, and then once there would stop moving (as the error is now ~0). So there'd be a fast change at the start edge of every audio sample. This would result in a higher energy at the sample rate than there would be from the other [pwm, random] methods, which have a slower change in output level.

Dougy the easy way to visualise a DS system is that is basically just sets a pin Hi or LO in the correct ratio, to give the desired average output. After very cycle the error is maintained and summed into the next bit cycle. So there is no long term error and it can give a fine resolution DAC result.

Example 25% PWM = 1000100010001000
Example 30% PWM = 10001001000100 (etc)

The math in the PIC is very simple and only requires an 8bit test and an 8bit addition or subtraction.
 
Status
Not open for further replies.

Latest threads

Back
Top