

/** INCLUDES *******************************************************/
#include <p18cxxx.h>
#include "bootloader.h"
#include "Rap_cyc.h"
#include "lcd_4b.h"




/** V A R I A B L E S ********************************************************/
unsigned char Rap_cyc=0;

#pragma udata

void int_ta1(void)
{
	if (PIR1bits.TMR1IF)
	{	
		T1CONbits.TMR1ON=0;
		if(Rap_cyc!=0)
			LATCbits.LATC2=1;
		PIR1bits.TMR1IF=0;
	}
}


void int_on_change(void)
{
	if (INTCONbits.RBIF)
	{	
		short int RapCyc_timer;
		unsigned char valeur_RB4;
		unsigned char data;
	
		valeur_RB4=PORTBbits.RB4;
		LATCbits.LATC2=0;
		RapCyc_timer=65535-(60000-((60000/100)*Rap_cyc));
		T1CONbits.TMR1ON=0;
	
		data = (RapCyc_timer >> 8);
		TMR1H = data;
		TMR1L = RapCyc_timer;

		T1CONbits.TMR1ON=1;
		INTCONbits.RBIF=0;
	}
	
	
}

#pragma interrupt YourHighPriorityISRCode
void YourHighPriorityISRCode()
{
}

#pragma interruptlow YourLowPriorityISRCode
void YourLowPriorityISRCode()
{
	int_on_change();
	int_ta1();
}

// Prototypes des fonctions de gestion du CAN

void init_can (void);
unsigned int convert (void);


//
void init_Timer1(void);
void init_portB(void);
void init_portC(void);

void main (void)
{
	unsigned char evolution, i=0;
	unsigned int CAN_val;


	init_port_lcd();
	init_lcd();

	init_can();
	init_aff();

	init_Timer1();
	init_portB();
	init_portC();
	
	INTCONbits.PEIE=1;

	// Program infinite Loop
	while(1)
	{
		CAN_val = convert ();

		if (CAN_val < 767)
		{
			if (Rap_cyc >= 50)
			{
				Rap_cyc = 0;
				evolution = 1;
			}
			else
			{
				Rap_cyc = 100;
				evolution = 0;
			}
			aff_rap_cyc (Rap_cyc);

			while (CAN_val < 767)
			{
				CAN_val = convert ();
				tpo_ms (100);
				i++;

				if (i == 10)
				{
					i = 0;
					if (evolution)
					{
						Rap_cyc += 20;
						if (Rap_cyc == 100)
							evolution = 0;
					}
					else
					{
						Rap_cyc -= 20;
						if (Rap_cyc == 0)
							evolution = 1;
					}
					aff_rap_cyc (Rap_cyc);
				}
			}
		}
	} // End of one loop iteration
}//end main

/** EOF main.c *************************************************/



//Initialisation du CAN
void init_can (void)
{
    ADCON1 = 0x0E;				// AN0 : analog input, Vref+ = Vdd, Vref- = Vss
    ADCON0 = 0x01;
	ADCON2 = 0x80;				
    TRISAbits.TRISA0 = 1;		
}

unsigned int convert (void)
{
    tpo_ms (5);
    ADCON0bits.GO = 1;        // starts conversion 
    while(ADCON0bits.GO);      
	return (ADRES);
}


void init_portC(void)
{
	TRISCbits.TRISC2=0;
	LATCbits.LATC2=0;
}

void init_portB(void)
{
	TRISBbits.TRISB4=1;
	INTCON2bits.RBIP=0;
	INTCONbits.RBIF=0;
	INTCONbits.RBIE=1;
	RCONbits.IPEN=1;
	INTCONbits.GIE=1;      
}

void init_Timer1(void)
{
	T1CON=0b10011000;
	PIE1bits.TMR1IE=1;
	IPR1bits.TMR1IP=0;
	PIR1bits.TMR1IF=0;
}


