# Pmw Question

## Recommended Posts

Hello,

I'm trying to use a PWM output (CCP1, RC2, Pin 17) from a 18F4420 to connect a servor motor (Futaba S3003).

The servo works with 20ms (50Hz).

The Pic runs wit an external OSC of 4Mhz.

Using the formula:

PWM Period = [(PR2) + 1] * 4 * TOSC * (TMR2 Prescale Value)

This is: [(78) + 1] * 4 * 4.10-6 * (16) = 20ms = 50Hz.

PR2 in my case is 78.

The configuration:

RC2 as output

void PWM()

{

t2con = 00000111b; // Timer2 =On, Prescaler 1/16.

ccp1con=00001100b; // PWM mode

pr2 = 78; // duty periode (50Hz = 78).

ccpr1l = 0x1F;

}

But if I connect an oscilloscope I get 800Hz (1,25ms)

What is wrong?

Thanks for help Martin

##### Share on other sites

Your math is wrong. I get 791Hz for your settings which is pretty close to what you measured.

Tosc when Fosc is 4 MHz is not 4us but 1/4000000 which is 0.25us (not 4us). This is your factor of 16 error.

So (PR2+1)*4*Tosc*Prescale is (78+1)*4*(1/4,000,000)*(16) = 1.264ms or 791 Hz

To get 50 Hz you need:

1/50 = (PR2+1)*4 * (1/4000000) * 16.

Solve for PR2 and you get:

PR2 = (1/50)*4000000/4/16 - 1 = 1250-1 or 1249

This does not fit so you need a larger prescale value which I do not see in the data sheet so you are out of luck.

The slowest you can go with a PR2 setting of 0xff and a 4MHz crystal is 244 Hz.

There is a note about using the Timer2 postscaler for servos but I did not look that closely.

Since your rate is so slow, you could do it the old fashioned way with interrupts and software counters and then you could have lots of PWM outputs for many servos.

I have a little toy example here:

Check out the BoostPWM files (there is a little plugin to show the PWM outputs).

Edited by trossin

##### Share on other sites

Thanks a lot for your help and the useful link. I'll try the old fashioned way.

Marrtin

## Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.