📄 pwmdemo.c
字号:
#include <pic18.h>#include "pwmdemo.h"void init(void);void get_period(void);void get_dutycycle(void);void update_pwm(void);unsigned int DUTYCYCLE=0x0080;unsigned char PERIOD=0xFF;unsigned int PERCENTAGE;unsigned char PRESCALE;void main(void){ init(); while(1) { get_period(); get_dutycycle(); update_pwm(); if (PERIOD==0) PERCENTAGE=0xFFFF; else PERCENTAGE=(DUTYCYCLE*100/PERIOD); }}void init(void){ GIE=0; /* no interrupts are used */ IPEN=0; TRISA=0x33; /* pin 0 & 1 are analog inputs */ /* pin 4 & 5 are inputs from DIP switch */ TRISC=0; /* PORTC.2 is the output from PWM */ ADCON1=0xC4; /* configure A2D */ CCP1CON=0x0F; /* select PWM mode */ }void get_dutycycle(void){ ADFM=1; /* need 10 bit result, right justify */ ADCON0=0xC9; /* select the channel of the duty cycle input pot */ GODONE=1; while(!ADIF)continue; ADIF=0; DUTYCYCLE=ADRES/3; /*right justified 10 bit result */}void get_period(void){ ADFM=0; /* period is an 8 bit value, left justify to get result from ADRESH */ ADCON0=0xC1; /* select the channel of the period input pot */ GODONE=1; /* start A2D */ while(!ADIF)continue; ADIF=0; PERIOD=ADRESH; /* Return 8 most signifigant bits of result */ } void update_pwm(void){ unsigned char dip_read;/* update the PWM period */ PR2=PERIOD;/* update the PWM duty cycle */ DC1B0=(bit)DUTYCYCLE; DC1B1=(bit)(DUTYCYCLE>>1); CCPR1L=(DUTYCYCLE>>2); /* update the timer 2 prescaler */ dip_read=DIP; if (dip_read == 0) PRESCALE=1; else if (dip_read == 1) PRESCALE=4; else PRESCALE=16; T2CON=(0x04+dip_read);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -