#include "stm32f10x.h"
#include "../Include/PWM.h"


void MyTimer_PWM(TIM_TypeDef *Timer, char Channel) { // Activer PWM sur un output
    // preload
    Timer->CR1 |= TIM_CR1_ARPE;

    switch (Channel) {
        case 1:
            // Config o channel 1 in "PWM Mode 1" and enable preload of CCR1
            Timer->CCMR1 &= ~TIM_CCMR1_OC1M; // clean bit modes
            Timer->CCMR1 |= TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1; // Mode PWM 1
            Timer->CCMR1 |= TIM_CCMR1_OC1PE; // enable preload

            // enable exit 1 (Output enable)
            Timer->CCER |= TIM_CCER_CC1E;
            break;
        case 2:
            Timer->CCMR1 &= ~TIM_CCMR1_OC2M;
            Timer->CCMR1 |= TIM_CCMR1_OC2M_2 | TIM_CCMR1_OC2M_1;
            Timer->CCMR1 |= TIM_CCMR1_OC2PE;
            Timer->CCER |= TIM_CCER_CC2E;
            break;
        case 3:
            Timer->CCMR2 &= ~TIM_CCMR2_OC3M;
            Timer->CCMR2 |= TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1;
            Timer->CCMR2 |= TIM_CCMR2_OC3PE;
            Timer->CCER |= TIM_CCER_CC3E;
            break;
        case 4:
            Timer->CCMR2 &= ~TIM_CCMR2_OC4M;
            Timer->CCMR2 |= TIM_CCMR2_OC4M_2 | TIM_CCMR2_OC4M_1;
            Timer->CCMR2 |= TIM_CCMR2_OC4PE;
            Timer->CCER |= TIM_CCER_CC4E;
            break;
    }

    // special case(specific timers)
    if (Timer == TIM1 || Timer == TIM8) {
        Timer->BDTR |= TIM_BDTR_MOE;
    }
}
void MyTimer_Set_DutyCycle(TIM_TypeDef *Timer, char Channel, float DutyCycle_Percent) {
    unsigned short ccr_value;

    // Percentages between 0 and 100
    if (DutyCycle_Percent > 100.0) DutyCycle_Percent = 100.0;
    if (DutyCycle_Percent < 0.0) DutyCycle_Percent = 0.0;
    // calcule of crr
    ccr_value = (unsigned short)((DutyCycle_Percent / 100.0) * (Timer->ARR));
    // Assigner le valaur pour le registre de comparison pour le channel qui est pertient
    switch (Channel) {
        case 1:
            Timer->CCR1 = ccr_value;
            break;
        case 2:
            Timer->CCR2 = ccr_value;
            break;
        case 3:
            Timer->CCR3 = ccr_value;
            break;
        case 4:
            Timer->CCR4 = ccr_value;
            break;
    }
}
