/* 
 * File:   JVC_IR.h
 * Author: Rodrigo
 *
 * Created on 26 de diciembre de 2012, 10:25
 */

#ifndef JVC_IR_H
#define	JVC_IR_H

/*---------- Configuration ----------*/
#define Xtal    12000000    // 12MHz Xtal
#define Freq    38000       // 38Khz Carrier frequency
#define Duty    0.33        // 33% Duty Cycle
#define PS      1           // Prescaler 1:1

/*---------- Calculation of the PWM FRequency & Duty Cicle ----------*/
#define JVC_PWM_Freq    (Xtal)/(Freq * 4 * PS)
#define JVC_PWM_Duty    (Duty * Xtal)/(Freq * (1/PS))

/*---------- Prototypes ----------*/
void JVC_Command_ON(void);
void JVC_Command_OFF(void);
void JVC_PWM_Start_Burst(void);
void JVC_Initialize(void);
void JVC_PWM_1(void);
void JVC_PWM_0(void);

/*---------- Function: Initialize the PWM1, Timer2 ----------*/
void JVC_Initialize(void){

    TRISC = 0;

    OpenTimer2(TIMER_INT_OFF & T2_PS_1_1 & T2_POST_1_1); //Prescaler 1:1 & Postscaler 1:1
    SetDCPWM1(JVC_PWM_Duty); // JVC IR protocol PWM Duty Cycle
}

/*---------- Function: Send the ON sequense to the PWM ----------*/
void JVC_Command_ON(void) {

    int i;
    char Command_ON[33] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1};

    JVC_PWM_Start_Burst();
    for (i = 0; i <= 33; i++) {
        if (Command_ON[i] == 1) {
            JVC_PWM_1();
        } else if (Command_ON[i] == 0) {
            JVC_PWM_0();
        }
    }
    ClosePWM1();
}

/*---------- Function: Send the OFF sequense to the PWM ----------*/
void JVC_Command_OFF(void) {

    int i;
    char Command_OFF[33] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1};

    JVC_PWM_Start_Burst();
    for (i = 0; i <= 33; i++) {
        if (Command_OFF[i] == 1) {
            JVC_PWM_1();
        } else if (Command_OFF[i] == 0) {
            JVC_PWM_0();
        }
    }
    ClosePWM1();
}

/*---------- Function: Start burst for the JVC protocol ----------*/
void JVC_PWM_Start_Burst(void) {
    OpenPWM1(JVC_PWM_Freq);
    Delay100TCYx(252);
    ClosePWM1();
    Delay100TCYx(126);
}

/*---------- Function: Binary 1 for the JVC protocol ----------*/
void JVC_PWM_1(void) {
    OpenPWM1(JVC_PWM_Freq);
    Delay10TCYx(158);
    ClosePWM1();
    Delay100TCYx(63);
}

/*---------- Function: Binary 0 for the JVC protocol ----------*/
void JVC_PWM_0(void) {
    OpenPWM1(JVC_PWM_Freq);
    Delay10TCYx(158);
    ClosePWM1();
    Delay10TCYx(158);
}

#endif	/* JVC_IR_H */

