📄 ledpwm.c
字号:
#include "config.h"
#include "serial.c"
#include "serio.c"
// generates a PWM square wave using timer 2 and the CCP module //
// reads A/D value and uses this as PWM value //
// assumes LEFT JUSTIFICATION //
void update_pwm(void){
unsigned char rval1;
rval1 = ADRESH;
CCPR1L = rval1;
rval1 = ADRESL;
if (bittst(rval1,7)) bitset(CCP1CON, 5);
else bitclr(CCP1CON, 5);
if (bittst(rval1,6)) bitset(CCP1CON, 4);
else bitclr(CCP1CON, 4);
// start new conversion //
GODONE = 1; // start conversion //
}
unsigned char do_update_pwm;
#if defined(HI_TECH_C)
void interrupt timer2_isr(void)
#endif
#if defined(__18CXX)
#pragma interrupt timer2_isr
void timer2_isr(void)
#endif
{
update_pwm();
TMR2IF = 0; // clear timer2 interupt flag //
}
void main(void){
serial_init(95,1); // 19200 in HSPLL mode, crystal = 7.3728 MHz
if (POR == 0){ // bit 2 in RCON register, cleared to 0 on power-up reset
POR = 1; // setting to bit to 1 means that will remain a '1' for MCLR reset
printf("Power-on reset has occurred.");
pcrlf();
}
if (TO == 0) {
SWDTEN = 0; // disable watchdog timer
printf("Watchdog timer reset has occurred, press reset to recover.\n");
pcrlf();
while(1);
}
SWDTEN = 1; // enable watchdog timer
// configure A/D inputs of PORT A to be all digital inputs //
ADCON1 = 0x0E; // Port A analog input, left justification of result //
TRISA = 0xFF; // all bits input //
ADCON0 = 0x80; // sampling freq = Fsoc/32, channel 0 //
ADON = 1; // turn on ADC
printf("ADC is configured!!!");
pcrlf();
// configure timer 2//
// pre scale of 16
T2CKPS1 = 1;
// start timer 2
TMR2ON = 1 ;
// set up PWM //
PR2 = 255; // set timer2 PR register, always set for 225 for this choice //
CCPR1L = (255 >> 1); // 50% duty cycle //
bitclr(CCP1CON, 5);
bitclr(CCP1CON, 4);
// set CCP1 output
TRISC2 = 0;
// PWM Mode
bitset(CCP1CON, 3);
bitset(CCP1CON, 2);
// enable interrupts
IPEN = 0; // priorities disabled //
TMR2IF = 0; // clear timer2 interupt flag //
TMR2IE = 1; // receive interrupt enable //
PEIE = 1;
GIE = 1;
while(1) {
// let interrupt do all of the work //
CLRWDT(); //asm("clrwdt");
}
}
//for MCC18, place the interrupt vector goto
#if defined(__18CXX)
#if defined(HIGH_INTERRUPT)
#pragma code HighVector=HIGH_INTERRUPT
#else
#pragma code HighVector=0x0008
#endif
void HighVector (void)
{
_asm goto timer2_isr _endasm
}
#pragma code
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -