#include "DCMotor.h"
#include "math.h"

void DCMotor_conf(TIM_TypeDef * timer, int channel, GPIO_TypeDef * gpio, int pin)
{
	//On règle la vitesse en valeur absolue, ici à 0
	Timer_pwmo_conf(timer, channel, 50, 0);
	
	//On règle le sens du moteur, ici sens direct (?)
	GPIO_conf(gpio, pin, LL_GPIO_MODE_OUTPUT, LL_GPIO_OUTPUT_OPENDRAIN, LL_GPIO_PULL_DOWN);
	GPIO_setPin(gpio, pin, 0);
}

void DCMotor_setSpeed(TIM_TypeDef * timer, int channel, GPIO_TypeDef * gpio, int pin, float speed)
{
	const int dir = (speed > 0.) ? 1 : 0;
	
	Timer_pwmo_setDutyCycle(timer, channel, fabs(speed));
	GPIO_setPin(gpio, pin, dir);
}

float DCMotor_getSpeed(TIM_TypeDef * timer, int channel, GPIO_TypeDef * gpio, int pin)
{
	const float speedAbs = Timer_pwmo_getDutyCycle(timer, channel);
	const int dir = GPIO_readPin(gpio, pin);
	
	return dir ? speedAbs : -speedAbs;
}
