# Using PWM on a 18F13K22

Discussion in 'Microcontrollers' started by MrDEB, Nov 27, 2013.

1. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
LOL Little Ghostman! Exactly what I was thinking.

2. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
Here's a simple way to understand aliasing when digitally sampling data, thanks to Glenn White. When data is digitally sampled, discrete data points are measured periodically. This is like looking at the data through the gaps between the boards in a picket fence – you can see what's happening at each gap, but you don't know what's happening between the gaps. Look at the top half of the top graph below. The red dots are the data we sample, and the red dashed line is what we believe to be happening. The bottom half of the top graph shows the true data that was sampled. Notice that the data has been sampled twice for each period of the square wave.

Now low at the top plot in the lower section. Every time the data was sampled, the value was zero, and the dashed red line is what we must conclude the data looks like – a straight line at zero.

But look at the bottom section. The real data is a square wave, but because we sampled too slowly, all we saw was zero values. Depending on when we started sampling, the sampling might have returned all high values, and we'd think it was a straight line at the high state. If the sample rate is less than twice the highest frequency of the data, it will alias – it will look like something it's not.

MrDEB's data is aliased because the sample rate was too low. There is no way to tell from the measurement what the data actually looked like.

3. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
So it seems MrDEB may have noticed the two plots he posted were vastly different, he didn't let that bother him too much, and saw the results he wanted to see.

When the fact that his plots looked nothing at all like a PWM signal was explained to him, along with the reason why his plots weren't worth the bits to store them, the response was:

Maybe this will help someone using the logic tool? Maybe? Someone? Not "That explains why my data looks like garbage. Here's what it looks like after I took the 30 seconds to make a proper measurement."?

And then a detailed explanation of aliasing isn't acknowledged at all.

Once again, it has been a truly a rewarding and gratifying experience to futilely attempt to help MrDEB.

Joined:
Jan 12, 1997
Messages:
-
Likes:
0

5. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA

One final post to clarify sample rate issues....

In this case, we know the PWM signal is modulated at 5 kHz, so we know that we need a sample rate of more than 10 kHz. But what about a case where the frequency of the pulse train is unknown? How do we know what sample rate is needed?

The secret is to start at the highest sample rate possible to get an idea of what the data looks like. The plots below show a 5 kHz 90% duty cycle signal at the available sample rates of the PICkit 2 logic analyzer. The top trace is with a 1 MHz sample rate, and shows just a few periods of the signal. This is useful to measure the period of of the waveform with good resolution; we could calculate the frequency accurately from this measurement.

The wave forms down the chart show the effect of decreasing the sample rate. The waveform is scrunched together, but more of it is shown. The lower sample rates are good for observing missing pulses, varying duty cycles or frequencies and even decoding the bit stream of serial data.

The data gets more and more scrunched together until finally at a 10 kHz sample rate, the pattern falls apart. This data has been aliased because the sample rate is too low. The measurement is garbage at this point and does not reflect reality.

So the answer is pretty simple. Start at the highest frequency possible. This allows you to see a small portion of the waveform with good resolution. Decease the sample rate to see longer periods of the signal. When the signal falls apart, you've gone too far. Each of these measurements took literally a few seconds, so the time to do it right isn't much longer than the time to get garbage.

This post is for those who may be trying to learn something from MrDEB's follies. I'm certain he won't be interested.

6. ### ericgibbsWell-Known MemberMost Helpful Member

Joined:
Jan 4, 2007
Messages:
21,240
Likes:
645
Location:
Ex Yorks' Hants UK
ONLINE
hi Jon,
I see that you have put a lot of technical work and time into your posts to this thread, have you considered creating and posting an Article for this topic?
I am sure that many will appreciate your work.

Eric

• Agree x 2
7. ### misterTWell-Known MemberMost Helpful Member

Joined:
Apr 19, 2010
Messages:
2,697
Likes:
368
Location:
Finland
This is true, but it is only a theory. In practice you would want to sample about five times in one cycle (of the highest sine freq.). If you have proper low-pass filtering etc.
Sampling at twice the highest frequency is just the absolute theoretical limit where you have the slightest theoretical chance to recreate the waveform you just sampled.

Last edited: Jan 28, 2014
• Agree x 1
8. ### MrDEBActive Member

Joined:
Apr 16, 2007
Messages:
4,414
Likes:
23
As I was viewing the logic tool I did view all the different sample rates and investigated the different signal outputs by sliding the view bar across the bottom of the view window. I found the wave changes as I went from left to right. I didn't realize about the alliseding.
Thanks for all the interesting reading. I have a folder which I put sections of this thread into for reference as I do for most all my projects.
The dinner was a success. We made 60 pounds of Italian sausage and 1,077 meatballs. The candles looked great but going to make more for next year.
Now I am cleaning up my beer cooler code and adding a few options. Taking Burts comment to heart and not use any interrupts.

9. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
True points misterT. The PICkit 2 logic analyzer is a simple quick&dirty tool and I was gearing my discussion towards it. Nyquist actually says 2.5 times I believe. The data I posted last night with a 5 kHz signal is aliased when sampled at 10 kHz, so it's definitely greater than 2x.

My background is machinery vibration analysis using audio range FFT analyzers (such as the HP 3561A) and digital data collectors, which all have brick-wall anti-aliasing filters to prevent this from happening. It can be a challenge looking at a time domain signal when trying to analyze some "click...click...click..." impact noise. You can see one burst in the time domain, but if you slow the sample rate down in an effort to see several bursts to measure the repetition rate of the bursts, the anti-aliasing filter has removed all of the energy of the "click."

Thanks for the suggestion Eric. I think there's almost enough info here for an article – it shouldn't be buried in a 20 page forum post. I'll work on fleshing it out. The PICkit 2 is a versatile tool to have available.

10. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
"I didn't realize about the alliseding." I think this one sentence explains so much.

Proper use of the logic tool to prevent aliasing is a pretty simple concept once explained, so I should think understanding it and filing it in your head would be the most effective place to put it. *Shrug* That's just me.

11. ### ericgibbsWell-Known MemberMost Helpful Member

Joined:
Jan 4, 2007
Messages:
21,240
Likes:
645
Location:
Ex Yorks' Hants UK
ONLINE
Jon,
http://www.electro-tech-online.com/posts/1161883/

Eric

• Agree x 1
12. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
One final post to wrap this up. The chip I used for the PWM testing above was an 18F25K20, which happens to have the same ECCP module with steering as the 18F13K22, so I decided to check out the steering feature since MrDEB did not provide any real measurement showing the in phase/out of phase feature.

I used the settings from Tumbleweed's code back on page 17 of this saga, and measures P1A and P1B.

Code (text):

// this assigns PWM output onto P1A, P1B, and P1C pins
// Note: The PWM Steering mode is available only when the CCP1CON register bits
// CCP1M<3:2> = 11 and P1M<1:0> = 00. Also, the TRIS bits must be set to output
// mode ('0') to enable the pin output driver in order to see the PWM signal on the pin
PSTRCON = \$07  // sets all outputs

// P1A-P1B polarity
// CCP1CON bits 3-0 CCP1M<3:0>: Enhanced CCP Mode Select bits
// 1100 = PWM mode; P1A, P1C active-high; P1B, P1D active-high
// 1101 = PWM mode; P1A, P1C active-high; P1B, P1D active-low
// 1110 = PWM mode; P1A, P1C active-low; P1B, P1D active-high
// 1111 = PWM mode; P1A, P1C active-low; P1B, P1D active-low
//
// calling pwm.Start1() sets CCP1CON = \$0C, so bits[3:0] = 1100 (setting all active high)
// to get P1A and P1B opposite, try setting bit1 = 0 and bit0 = 1
CCP1CON.bits(1) = 0
CCP1CON.bits(0) = 1

Using the CCP1CON settings above, the P1A and P1B signals are in phase as shown below with the same 5 kHz, 90% duty cycle signal used above. In fact, no combination of these two bits resulted in out of phase signals, and I didn't have enough interest to dig deeper into the problem.

See Following Posts For Steering Test Results

The top trace is sampled at 1 MHz to give good resolution. The bottom trace is sampled at 100 kHz to show the series.

Last edited: Jan 29, 2014
13. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
Speaking of not getting what you think you're getting, the 90% duty cycle is HIGH 90% of the time. If you have an LED connected between V+ and the port pin such that a LOW port pin turns it on, the duty cycle would be inverted. This 90% duty cycle would be effectively a 10% duty cycle.

14. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
I just realized what the problem may be....it's actually spelled out in Tumbleweed's comments in the code:

"Calling pwm.Start1() sets CCP1CON = \$0C, so bits[3:0] = 1100 (setting all active high) . To get P1A and P1B opposite, try setting bit1 = 0 and bit0 = 1."

I set the CCP1CON bits before I started the PWM module, so the start command reset the bits to (00). That's what happens when I do things on the spur of the moment late at night. I will try this again later today.

15. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
As I realized, setting the CCP1CON bits after the PWM.Start1 command solved the steering issue. The plots below show the results.

With CCP1CON(1,0) = 0,0, P1A (bottom trace of the pair) and P1B are in phase.

With CCP1CON(1,0) = 0,1, P1B is inverted.

With CCP1CON(1,0) = 1,0, P1A is inverted.

With CCP1CON(1,0) = 1,1, both P1A and P1B are inverted.

Not that this has anything to do with the subject at hand....

16. ### MrDEBActive Member

Joined:
Apr 16, 2007
Messages:
4,414
Likes:
23
I had the CCP1CON in the PWM2 module but set the wrong bits. I never tried running with the correct CCP1CON in the PWM2 module
Code (text):
{
****************************************************************************
* Name    : Start1                                                         *
* Purpose : Start PWM Channel 1                                            *
****************************************************************************
}
Public Sub Start1()
CCP1CON = \$0c    ' \$0c  PWM mode P1A, P1C active high :P1B, P1D active high
Output(FPWM1Pin)
Output(FPWM2Pin)
Output(FPWM3Pin)
FTMR2ON = 1
PSTRCON = \$0F       ' PWM output steering register
End Sub
{
but need to set bit 1 and 0
correct bit settings
CCP1CON.bits(1) = 0
CCP1CON.bits(0) = 1

17. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
Huh? Since you apparently never took a valid measurement with the logic analyzer, how do you know what you had?

18. ### MrDEBActive Member

Joined:
Apr 16, 2007
Messages:
4,414
Likes:
23
I tried several sample rates but none were 180 degrees out of phase until I put the
CCP1CON.bits(1) = 0
CCP1CON.bits(0) = 1
as they should be. The 180 out of phase adds to the candle effect which is what I was after.

19. ### Little GhostmanWell-Known MemberMost Helpful Member

Joined:
Jan 7, 2011
Messages:
3,737
Likes:
433
Location:
SCOTLAND
in phase out of phase, makes no difference after a certain frequency, as you cant tell the difference anyway.

20. ### JonSeaWell-Known Member

Joined:
Oct 1, 2012
Messages:
1,201
Likes:
111
Location:
Seattle, WA
Good point LG. The eye can't tell over about 24 Hz – certainly at the 5 kHz the PWM is running at, the eye can't see the difference.

But I also can't understand the belief that somehow when yellow is bright, red should be dim and vice versa. Using this scheme, it's always one or the other. There is no dim or off state. I don't think it's doing what MrDEB thinks (or desires) it does.

21. ### Little GhostmanWell-Known MemberMost Helpful Member

Joined:
Jan 7, 2011
Messages:
3,737
Likes:
433
Location:
SCOTLAND
In the end, all that is needed is loops inside loops. I will ask 3V0 if I can post the code he did for dad, it was for something very special that needed a RGB. 3V0 very kindly gave my dad the bare bones solution.
It will make any colour any time on any chip. I still look at it, and everytime I do it makes me want to be that good one day.
NO TIMERS, NO PWM modules, NO TRICKERY! Just Loops inside Loops, Its about as clean and clever as it get's.
He also made a very complex 12 fan controller, this thing is beyond words, each fan can do its own thing and can run any pattern! a real master piece of code.
12 channels of independent PWM! Again not a single PWM mod or timer or interrupt! and yet even using 8MHz internal OSC, the processor still has time to go make you hot chocolate and bake you a cake!
Again all done with Loops inside loops.
Not sure if you know this Mr Deb, but 180 degrees out of phase, just means when one pin is on, the other is off.
so not sure what the syntax in basic is, but in pseudo code to get it you simply do this.
say you have pwm output on pin B6

PinB5 NOT=Pin6

thats it.