#include "servo.h"
#include "stm32g4xx.h"
#include "gpio.h"


static void InitTIM16(TIM_TypeDef* TIM, unsigned long Freq, unsigned long CCER)
{
  TIM->ARR = (1000000/Freq) - 1;
  TIM->PSC = (SystemCoreClock / (1000000/Freq) / Freq) - 1;
  TIM->CCMR1 = TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1PE | TIM_CCMR1_OC2M_1 | TIM_CCMR1_OC2M_2 | TIM_CCMR1_OC2PE;
  TIM->CCMR2 = TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3PE | TIM_CCMR2_OC4M_1 | TIM_CCMR2_OC4M_2 | TIM_CCMR2_OC4PE;
  TIM->CCER = CCER;
  TIM->BDTR = TIM_BDTR_MOE;
  TIM->CCR1 = 0;
  TIM->CCR2 = 0;
  TIM->CCR3 = 0;
  TIM->CCR4 = 0;
  TIM->CR1 = TIM_CR1_CEN;
}
//------------------------------------------------------------------------------

void Servo_init(unsigned long Freq)
{
  RCC->APB1ENR1 |= RCC_APB1ENR1_TIM2EN;
  RCC->APB2ENR |= RCC_APB2ENR_TIM1EN | RCC_APB2ENR_TIM16EN | RCC_APB2ENR_TIM17EN;
  RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN;

  
  GPIO_InitPin(GPIO_PIN_12 | GPIO_PORT_A | GPIO_ALTER | GPIO_AF1);  // TIM16_CH1
  

  InitTIM16(TIM16, Freq, TIM_CCER_CC1E);

}
//------------------------------------------------------------------------------

void Servo_update(unsigned short Pow)
{
  TIM16->CCR1 = Pow;

}

//------