#include "Driver_TIMER.h" 

//réservation d'un espace mémoire pour un pointeur de fonction associé à chacun des timers
void (* IT_function_TIM1) (void) = 0x0; 
void (* IT_function_TIM2) (void) = 0x0; 
void (* IT_function_TIM3) (void) = 0x0; 
void (* IT_function_TIM4) (void) = 0x0; 

void MyTimer_Base_Init(MyTimer_Struct_TypeDef * Timer) {
	Timer -> Timer -> ARR = Timer -> ARR -1;
	Timer -> Timer -> PSC = Timer -> PSC -1;
}

void Activate_TIM(int i) {
	if (i==1) {
		//le timer1 est sur apb2enr
		RCC-> APB2ENR |= 0x01 << 11 ;
	}
	else {
		//les autres timers sont sur apb1enr
		RCC-> APB1ENR |= 0x01 << (i-2) ;
	}
}

void MyTimer_Active_IT ( TIM_TypeDef * Timer , char Prio , void (* IT_function) (void)) {
	//active l'interruption sur timer et pointe vers la fonction IT_function avec la priorité prio

	//"Trigger DMA request enabled"
	Timer -> DIER |= 1;
	
	if (Timer == TIM1) {
		NVIC_EnableIRQ(TIM1_TRG_COM_IRQn);
		NVIC_SetPriority(TIM1_TRG_COM_IRQn, Prio);
		IT_function_TIM1 = IT_function ;
	}
	else if (Timer == TIM2) {
		NVIC_EnableIRQ(TIM2_IRQn);
		NVIC_SetPriority(TIM2_IRQn, Prio);
		IT_function_TIM2 = IT_function ;
	}
	else if (Timer == TIM3) {
		NVIC_EnableIRQ(TIM3_IRQn);
		NVIC_SetPriority(TIM3_IRQn, Prio);
		IT_function_TIM3 = IT_function ;
	}
	else if (Timer == TIM4) {
		NVIC_EnableIRQ(TIM4_IRQn);
		NVIC_SetPriority(TIM4_IRQn, Prio);
		IT_function_TIM4 = IT_function ;
	}
}

void TIM1_TRG_COM_IRQHandler(void) {
	//on met à 0 le flag d'interruption
	TIM1->SR &= ~1;
	if (IT_function_TIM1)
	(* IT_function_TIM1) ();
}

void TIM2_IRQHandler(void) {
	//on met à 0 le flag d'interruption
	TIM2->SR &= ~1;
	if(IT_function_TIM2)
	(* IT_function_TIM2) ();
}

void TIM3_IRQHandler(void) {
	//on met à 0 le flag d'interruption
	TIM3->SR &= ~1;
	if(IT_function_TIM3)
	(* IT_function_TIM3) ();
}

void TIM4_IRQHandler(void) {
	//on met à 0 le flag d'interruption
	TIM4->SR &= ~1;
	if(IT_function_TIM4)
	(* IT_function_TIM4) ();
}
