#include <xc.h>
#include "config.c"
#include <stdint.h>
#define _XTAL_FREQ 32000000
#define NUM_SERVOS 10
uint16_t wordTemp;
uint32_t ms;
uint8_t count=0,servoCount;
uint16_t servoPos[NUM_SERVOS];
void main(void) {
OSCCON=0b01110000; //8MHz
PLLEN=1; //x4=32MHz
//setup 1mS interrupt = 8,000,000/16 = 500,000/10 = 50,000 set PR2=49 = 50,000/50 = 1000 = 1mS
T2CON=0b01001110; //pre=16 post=10
PR2=49;
TMR2IE=1; //timer 2 interrupts enable
T1CON=0; //timer 1 stopped
for(uint8_t i=0;i<NUM_SERVOS;i++){
servoPos[i]=i*1000+8000; //1ms(8000) to 1.875(7/8ths - 15000)ms in 1/8th mS steps
}
TRISC=0b11111100; //CCP0 & 1 output
PEIE=1;
GIE=1;
while(1){
//adjust servo positions here
}
}
void __interrupt() inter(void){
if(TMR2IE && TMR2IF){
ms++;
count++;
if(count>=20){ //start every 20mS
TMR1=0; //zero timer 1
T1CON=1; //start timer 1
count=0;
CCP1CON=0b1000; //CCP1 pin low and high on match - will be first pulse
CCPR1L=0x0d;
CCPR1H=0x07;
CCP1IE=1; //enable CCP1 interrupts
CCP1IF=0; //ensure interrupt flag is clear
servoCount=0; //reset servoCount
LATC0=1; //connected to data in of shift register will clock in a high when CCP1 goes high
}
TMR2IF=0;
}
if(CCP1IE && CCP1IF){
LATC0=0; //clear the data in pin
if(servoCount==9) //have we done all servos?
CCP1IE=0; //yes so no more CCP1 interrupts
if(CCP1CON==0b1000){ //have we started the 4000 cycle pulse
CCP1CON=0b1001; //yes so end the pulse after 0.5mS
wordTemp=CCPR1H*256+CCPR1L;
wordTemp=wordTemp+4000;
CCPR1L=wordTemp & 255;
CCPR1H=wordTemp/256;
}else{
CCP1CON=0b1000; //No so output the timed gap
wordTemp=CCPR1H*256+CCPR1L;
wordTemp=wordTemp-4000+servoPos[servoCount];
CCPR1L=wordTemp&255;
CCPR1H=wordTemp/256;
servoCount=servoCount+1;
}
CCP1IF=0;
}
}