/********************************************/
/*Timer Configuration Code                 */
/*dsPIC33CK512MP608                         */
/*                                          */
/*Timer 5 = programmable delay              */
/********************************************/

#include "xc.h" 
#include "MainMotion.h"

void Timer1_Init(void)
{   
    //Stop Timer1
    T1CON = 0;
    T1CONbits.TON = 0;// Disable Timer 
    
    T1CONbits.TCS = 0;// Select internal instruction cycle clock 
    T1CONbits.TGATE = 0;// Disable Gated Timer mode 
    T1CONbits.TCKPS = 3;
    TMR1 = 0x00; // Clear timer register 
    PR1 = 0xffff; // Load the period value 
    IPC0bits.T1IP = 0x01;// Set Timer 1 Interrupt Priority Level 
    IFS0bits.T1IF = 0;// Clear Timer 1 Interrupt Flag 
    IEC0bits.T1IE = 0;// Enable Timer1 interrupt 
    //T1CONbits.TON = 1;// Start Timer
}

//0 = 576nS
//1 = 1.04 uS
//10 = 1.2uS
//100 = 2.95uS
//1000 = ~21uS
void Delay(uint16_t delay_us)
{
    if(delay_us == 0)
    {
        return;
    }
    
    //65,535 max
    if(delay_us > 0xffff)
    {
        delay_us = 0xffff;
    }
    
    PR1 = delay_us;
    
    TMR1 = 0;
    
    IFS0bits.T1IF = 0;
    
    //Start Timer1
    T1CONbits.TON = 1;   
    
    while(!IFS0bits.T1IF);
    
    //Stop Timer1
    T1CONbits.TON = 0;   
}