%PWM Period Calculation for PIC18F4620

clc;
clear all;

%frequency desired
disp 'PWM PERIOD CALCULATION: PR2 value';
pwmfreq = 1000; %1kHz
disp 'Desired PWM Frequency in Hz =',disp (pwmfreq);
pwmprd = pwmfreq^-1;
disp 'Desired PWM Period in seconds =',disp (pwmprd);
fosc = 10e6; 
disp 'uC Oscillator Frequency (10 MHz crystal with 4 multiplier) ='
disp (fosc);
disp 'uC Oscillator Period (Tosc) in seconds =';
Tosc = fosc^-1;
disp (Tosc);
disp 'Timer2 Prescale Value (1, 4, or 16) =';
Tmr2prescl = 16;
disp (Tmr2prescl);
disp 'PR2 value =';
pr2 = (pwmprd/(4*Tosc*Tmr2prescl))-1;
pr2 = ceil(pr2);
disp (pr2)
disp 'Actual Frequency that will be produced in Hz';
mod_pwmprd = (pr2+1)*4*Tosc*Tmr2prescl;
mod_pwmfreq = mod_pwmprd^-1;
disp (mod_pwmfreq);
disp 'Rounded Frequency that will be produced in Hz';
disp (round(mod_pwmfreq));
disp '==============================='
disp '10-Bit CALCULATION (CCPRxL:CCPxCON<5:4>)';
disp 'Desired PWM Duty Cycle in seconds =';
pwmdtcyc = mod_pwmprd*0.2; %for 60% duty cycle
disp (pwmdtcyc);
disp 'Decimal form of (CCPRxL:CCPxCON<5:4>) ='
bit = pwmdtcyc/(Tosc*Tmr2prescl);
bit =  floor(bit);
disp (bit);
binbit = dec2base(bit,2);
disp 'Binary form of (CCPRxL:CCPxCON<5:4>) ='
disp (binbit);