/*
 * timer.cpp
 *
 *  Created on: 08. Aug. 2015
 *      Author: martin
 */

#include "stm32f4xx_hal.h"
#include "timer.h"
#include "globals.h"

//TIM2: APB1
// Timer channel 2 as base timer
void timer2Init()
{

	/* enable Clocks */
	__HAL_RCC_TIM2_CLK_ENABLE();

	// every 1ms an overflow
	initTimBase.Instance = TIM2;
	initTimBase.Init.CounterMode = TIM_COUNTERMODE_UP;
	initTimBase.Init.Period = 500;
	initTimBase.Init.Prescaler = 50;
	initTimBase.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	initTimBase.Init.RepetitionCounter = 0;

	HAL_TIM_Base_Init(&initTimBase);   //MspInit haben keinen Rückgabewert
	HAL_TIM_Base_Start_IT(&initTimBase);

	HAL_NVIC_SetPriority(TIM2_IRQn, 4, 1);
	HAL_NVIC_EnableIRQ(TIM2_IRQn);
}

void timer2PWMInit()
{

	/* enable Clocks */

	// every 1ms an overflow
	initTim2.Instance = TIM2;
	initTim2.Init.CounterMode = TIM_COUNTERMODE_UP;
	initTim2.Init.Period = 500;
	initTim2.Init.Prescaler = 1;
	initTim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	initTim2.Init.RepetitionCounter = 0;

	HAL_TIM_PWM_Init(&initTim2);
	timer2CH1PWMInit();
}


extern "C" void TIM2_IRQHandler(void)
{
	HAL_TIM_IRQHandler(&initTimBase);
}

// just defined interrupt function
/**
 * @brief  Period elapsed callback in non blockfaceing mode
 * @param  htim : TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	static uint32_t time = 0;
	time ++;

	// 1sek
	if(!(time % 1000))
	{
		if(htim->Instance == TIM2)
		{
			//HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
		}
	}
}

void timer2CH1PWMInit()
{
	initTim2CH1PWM.OCMode = TIM_OCMODE_PWM1;
	initTim2CH1PWM.OCPolarity = TIM_OCPOLARITY_HIGH;
	initTim2CH1PWM.OCFastMode = TIM_OCFAST_DISABLE;
	initTim2CH1PWM.Pulse = 100;
	HAL_TIM_PWM_ConfigChannel(&initTim2, &initTim2CH1PWM, TIM_CHANNEL_1);
	HAL_TIM_PWM_Start(&initTim2, TIM_CHANNEL_1);
}

/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
extern "C" void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
	__HAL_RCC_TIM2_CLK_ENABLE();
}

void setNewPWMValue()
{
	if(TIM2->CCR1 <= 400)
	{
		//initTim2CH1PWM.Pulse += 100;
		TIM2->CCR1  +=100;
	}
	else
	{
		//initTim2CH1PWM.Pulse = 0;
		TIM2->CCR1 = 0;
	}
	//HAL_TIM_PWM_ConfigChannel(&initTim2,&initTim2CH1PWM, TIM_CHANNEL_1);

}









#pragma GCC diagnostic pop

// ----------------------------------------------------------------------------

