Page 2 of 2

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 10:28 am
by AndrewB
I thought that the new PWM.bas would sort that side out?

I'm not sure how to read Setfrequency() and maxduty()

Could you give me an example of what I have to do for a 1khz frequency and 10bit input duty.

Thanks

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 11:15 am
by Jerry Messina
For a given system clock freq FOSC, as you increase the PWM freq the usable number of bits decreases.
Take a look at http://www.firewing.info/pmwiki.php?n=L ... lculations

For example if FOSC=32MHz and PWM freq=1000 then the max number of bits is ~8

Think of it this way: once you calculate the setting for the PWM period register, the duty cycle setting can't be any larger than that.
If the duty cycle setting = period register then that's 100%

Code: Select all
pwm.SetFrequency(1000)

// make sure adc reading is < pwm maxduty value
adc_val = adc.read(A2)
if (adc_val > pwm.MaxDuty()) then
   adc_val = pwm.MaxDuty()
endif   
   
pwm.write(whatever, adc_val)


If you want to use the adc, then write a function to scale the adc reading to MaxDuty

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 11:50 am
by AndrewB
Ok Thanks. Did not see the calculator.

How come the original pwm could be set at 1953Hz at 10 bit?

Frequency.Is1953Hz

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 11:54 am
by AndrewB
Oh Ok so if I reduce the OSC to 16
Timer Prescale to 8
I can get 977Hz? with 10 bit?

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 12:47 pm
by Jerry Messina
I think the 10-bit limitation came from the pic18. There the period reg is limited to 8-bits.

The pic24 can use 16-bits. The SetFrequency routine will calculate the smallest prescaler that will result in a 16-bit period reg setting for the freq you give it, and that then sets the max number of usable bits.

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 2:31 pm
by AndrewB
Sorry forgot to mention i'm using the pic24.

OK then I need to force prescale = &B00010000 and force the Osc to 16mhz?

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 4:20 pm
by Jerry Messina
Looking back at the spreadsheet I think I was off with those calcs before.
I don't think you'll have to force anything.

In the spreadsheet, set the prescaler = 1 and whatever osc value you want to use.
Adjust Timer Period (PR2) until the PWM Freq = 1000... looks like there's plenty of resolution for most settings.
For OSC=32MHz and pwm freq = 1000 --> prescaler=1 and PR2 = 16000 (13.9 bits)

The value in PR2 is the MaxDuty value you can use (16000).

Re: Simple PWM Module Example

PostPosted: Mon Nov 13, 2017 4:45 pm
by AndrewB
Thanks Jerry