#include "p33FJ64MC802.h"
#include<can.h>
#define Fbaud 1000000
#define Ftq Fbaud*20  // 20=Total Tq
#define BRP (Fcy/(2*Ftq)-1)
 		
void	ECAN_Init( void ) 
{ 		// Fecan=Fcy ,mode loopback, , mode continu, MODE CONFIGURATION
		CAN1SetOperationMode( 	CAN_IDLE_CON & CAN_MASTERCLOCK_0 &  
								CAN_REQ_OPERMODE_& CAN_CAPTURE_DIS) ; 
 
		while ( C1CTRLbits.OPMODE <= 3 ); 
			// on souhaite 1mbits/s
 			//PROPAGATIONTIME_SEG=5,SEG1=8,SEG2=6,SYNC_JUMP=2,
			//TOTAL TQ:1+ 5+8+6=20 page58 manuel ECAN
			// Ftq=20*1Mb/s= 20Mhz => 
			CAN1Initialize( CAN_SYNC_JUMP_WIDTH4 & CAN_BAUD_PRE_SCALE(BRP), 
							CAN_WAKEUP_BY_FILTER_DIS & 
							CAN_PHASE_SEG2_TQ(6) & 
							CAN_PHASE_SEG1_TQ(8) & 
							CAN_PROPAGATIONTIME_SEG_TQ(5) &  
							CAN_SEG2_FREE_PROG & CAN_SAMPLE1TIME ) ; 
 			// configure filtre 0: Filter Bits (11-bits): 0b001 1010 xxxx */
			CAN1SetFilter ( (char) 0 , CAN_FILTER_SID( 0x1D0) & CAN_RX_EID_DIS , 
			// configure masque 0: Masque Bits (11-bits): 0bxxx xxxx 0000 */
			// groupement d'adresse possible 0x1D0 à 0x1DF 
			CAN1SetMask ( 	(char)0 , CAN_MASK_SID ( 0x7F0 ) & CAN_MATCH_FILTER_TYPE ,  
							CAN_MASK_EID( 0x00) ) ;  
 
			CAN1SetTXMode( (char) 0 , CAN_TX_STOP_REQ & CAN_TX_PRIORITY_HIGH ) ; 
			CAN1SetRXMode( (char) 0 , CAN_RXFUL_CLEAR & CAN_BUF0_DBLBUFFER_EN ) ; 
 			// , MODE LOPPBACK, Fecan=Fcy ,mode loopback, , mode continu
			CAN1SetOperationMode(CAN_IDLE_CON & CAN_CAPTURE_DIS &
                         CAN_MASTERCLOCK_1 &
                         CAN_REQ_OPERMODE_LOOPBK); 
			while(C1CTRLbits.OPMODE !=2);							 
} 
