Assembly language PWM

Right so I am using a PIC18f4520

 

trying to get PWM working, I know how to selec the values for the PR2 register using the equation listed in the manual and also which prescale value to select, Its just how I write my code I am having trouble with.

 

I think I am missing something out, I know its only about 8 lines of code to use the pulsewidth modulation pin, is there any way someone could give me an example bit of code or at least list the steps to take to implement a code?

 

say I am using a 10MegXtal and the speed and duty cycle is up to you..

Ok, first up you’ll need

Ok, first up you’ll need to load the desired value into PR2:
MOVLW H’FF’
MOVWF PR2
This is the maximum value for PR2, which will result in the slowest PWM frequency for a given prescaler, change as required.

• Then we have the Timer2 config:
MOVLW B’0xxxx111’
MOVWF T2CON
You may already have a bit of code like this in your startup routine, if not just insert it along side all the other stuff. The 7th bit does nothing in this case, and the 4 bits following that set the Timer2 postscaler value, which is up to you depending on what Timer2 is used for in your program. Either way, the postscaler has no effect on the PWM module. Bit 2 needs to be a 1 in order to enable Timer2, and bits 0 & 1 are used to set the prescaler which does affect the PWM module. I’ve set the prescaler bits to 11 which sets the prescaler to 1:16, causing the PWM frequency to run 16 times slower.

• You’ll also need to make sure the appropriate PWM pins are configured as outputs. This has probably already been done in the startup section so I won’t cover it here.

• Adjust the duty cycle by loading a value to CCPR1L:
MOVLW H’33’
MOVWF CCPR1L

Just another randomly picked value, use the formula to get a real one.

• Finally you need to configure CCP1CON, which has control over the PWM module. You’ll want something like the following in your startup/reset routine:
MOVLW B’00111100’
MOVWF CCP1CON

The first 2 bits on the left (bits 6 & 7) set the extended PWM mode, 00 = single PWM using P1A, P1B/C/D are all left alone. The next two bits are the lower 2 bits of the 10bit duty cycle value, I’ve set them to 11 as a placeholder, you’ll have to change these to suit your needs. The 4 bits on the right set the CCP mode, 1100 = PWM with outputs active high. You can change this to be active low, or make some active low and others active high.

That’s all there is to it for normal, single PWM operation. The 18F4520 can run two PWM modules together, and they’ve got some extra advanced functions, but I wouldn’t worry about those until you’ve at least got the basic mode working.

You are a hero, got it

You are a hero, got it running this morning, it was the configuring the CCP1CON where I had the difficulties.

 

Cheers.

No probs, that’s what we’re

No probs, that’s what we’re here for. No wonder you were having trouble, all the good stuff is in CCPxCON =)

1 Like