#include "DcMotor.h"
#include "stm32f1xx_ll_gpio.h" 
#include "stm32f1xx_ll_bus.h"
#include "stm32f1xx_ll_tim.h" 

#define ARR_DC_MOTOR 50000
void DC_MOTOR_Init(void) {
	// use TIM2 since it has pa1 at channel 2 output
	// setup timer 2
	LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
	LL_TIM_InitTypeDef tim_init;
	// todo check switching behavior of the mosfet to determine period of switching 
	tim_init.Prescaler = 71;
	tim_init.Autoreload = ARR_DC_MOTOR - 1;
	tim_init.ClockDivision=LL_TIM_CLOCKDIVISION_DIV1;
	tim_init.CounterMode=LL_TIM_COUNTERMODE_UP;
	tim_init.RepetitionCounter=0;
	LL_TIM_Init(TIM2, &tim_init);
	
	// setup gpio
	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOA);
	LL_GPIO_InitTypeDef servo_gpio_init;
	servo_gpio_init.Pin = LL_GPIO_PIN_1;
  servo_gpio_init.Mode = LL_GPIO_MODE_ALTERNATE;
  servo_gpio_init.Speed = LL_GPIO_SPEED_FREQ_LOW;
  servo_gpio_init.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
	LL_GPIO_Init(GPIOA, &servo_gpio_init);
	
	// setup output compare
	LL_TIM_OC_InitTypeDef oc_init;
	oc_init.OCMode = LL_TIM_OCMODE_PWM1;
	oc_init.OCState = LL_TIM_OCSTATE_ENABLE;
	oc_init.OCNState = LL_TIM_OCSTATE_ENABLE;
	oc_init.CompareValue = 0; // off at start
	oc_init.OCPolarity = LL_TIM_OCPOLARITY_HIGH;
	oc_init.OCNPolarity = LL_TIM_OCPOLARITY_LOW;
	oc_init.OCIdleState = LL_TIM_OCIDLESTATE_LOW;
	oc_init.OCNIdleState = LL_TIM_OCIDLESTATE_HIGH;
	LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH2, &oc_init);
	LL_TIM_EnableCounter(TIM2);
	
	// init gpio for direction (sense) pin
	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOA);

	
	LL_GPIO_InitTypeDef pa2_init_conf;
	pa2_init_conf.Mode = LL_GPIO_MODE_OUTPUT;
	pa2_init_conf.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
	pa2_init_conf.Speed = LL_GPIO_SPEED_FREQ_LOW;
	pa2_init_conf.Pin = LL_GPIO_PIN_2;
	LL_GPIO_Init(GPIOA, &pa2_init_conf);

}

void DC_MOTOR_SetSpeed(int speed){
	if(speed <= 100 && speed >= 0){
		LL_GPIO_SetOutputPin(GPIOA,LL_GPIO_PIN_2);
		int converted_speed = speed * (ARR_DC_MOTOR / 100);
		TIM2->CCR2 = converted_speed;		
	} else if (speed >= -100 && speed <= 0) {
		LL_GPIO_ResetOutputPin(GPIOA,LL_GPIO_PIN_2); // TODO maybe switch around set and reset, depending on direction of turning
		int converted_speed = (-1) * speed * (ARR_DC_MOTOR / 100);
		TIM2->CCR2 = converted_speed;	
	} else {
		TIM2->CCR2 = 0;
	}
}
