源文件pwm.c
#include "pwm.h"
// 频率 占空比 极性
void Pwm1_Init(volatile U16 frequency, volatile U16 duty, volatile U16 polar) {
// 周期,单位是ms
volatile U16 period = 1000 / frequency; //32.25ms(T=1/F=1/0.032S=1000/32ms)
// volatile U16 PWM1P = period * 128;// 系统选择的内部低速时钟128K
volatile U16 PWM1P = period * 24000;// 系统选择的24M
// volatile U16 PWM1D = (PWM1P / 100) * duty;
volatile U16 PWM1D = (PWM1P * duty )/ 100; // duty/100=PWM1D/PWM1P
_push_(INSCON);
INSCON &= 0xbf; // Bank0
// 周期寄存器12位, 0x0fff=4095,周期=4095/128K=0.0319s=32ms
// 通过周期计算PWM0Px的值,PWM0Px=period*128K/1000
PWM1PL = PWM1P & 0xff; //PWM输出周期=[PWM1PH,PWM1PL]*PWM时钟周期
PWM1PH = PWM1P >> 8;
// 占空比寄存器,0x07ff=2047
// 计算占空比寄存器的值,PWM0Dx=周期寄存器值*duty/100
PWM1DL = PWM1D & 0xff;
PWM1DH = PWM1D >> 8;
if (polar == 1) {
PWM1CON |= 0x40;
} else {
PWM1CON &= 0xbf;
}
// PWM1控制寄存器 1100_0001,使能、占空比期间输出低电平、占空比溢出后输出高电平、输出允许
PWM1CON |= 0x81;// PWM输出周期=fosc/1(不分频)
_pop_(INSCON);
}
void set_pwm_init(){
//unsigned char SYSCLK = 24; // 24MHz
//unsigned char PWM1CONINIT0 = 0x00;
//unsigned char PWM1CLKINIT = 0x01;
//
//unsigned long PWM1FREQINIT = 1000 ;// PWM输出频率 1000hz
#define PWM1DUTYINIT0 90 // PWM占空比
//unsigned char PWM1DUTYINIT0;
//