/*
 *  Interrupt and PWM utilities for 16 bit Timer1 on MG32x02z
 *  Original code by Cuijian May 2024
 *
 *  This is free software. You can redistribute it and/or modify it under
 *  the terms of Creative Commons Attribution 3.0 United States License. 
 *  To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/us/ 
 *  or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
 *
 */

#if defined(MG32F02U128) 

#include "TimerOne.h"
#include "timer.h"
#include "pwm.h"

//TimerHandleDeinit(timer_id_e timer_id)

void ftm1_isr(timer_id_e TmId);

TimerOne Timer1;              // preinstatiate

void (*TimerOne::m_isrCallback)() = TimerOne::isrDefaultUnused;

void TimerOne::isrDefaultUnused()
{
    ;
}




void TimerOne::initialize(unsigned long microseconds)
{
    setPeriod(microseconds);
    //TimerHandleStop(USED_TIMERONE_ID);

    TimerAttachIntHandle( USED_TIMERONE_ID, ftm1_isr  );
    start();
}

void TimerOne::setPeriod(unsigned long microseconds)
{
    m_microseconds = microseconds;
    TimerHandleInitByPeriod( USED_TIMERONE_ID,  m_microseconds );
}


void ftm1_isr(timer_id_e TmId)
{
    TmId = TmId;
    if( NULL != Timer1.m_isrCallback )
    {
        Timer1.m_isrCallback();
    }

}




void TimerOne::setPwmDuty(char pin, unsigned int duty)
{
    if( duty<=1024 )
    {
        m_duty = duty;
    }
    else 
    {
        m_duty = duty%1024;
    }

    if( (pin == TIMER1_A_PIN)
     || (pin == TIMER1_B_PIN) )
    {
        m_pin = pin;
    }
    else 
    {
        m_pin = 0xFFFF;
    }
}

void TimerOne::pwm(char pin, unsigned int duty)
{
    uint32_t  frequency;
    
    stop();
    setPwmDuty(pin, duty);
    if( m_pin == 0xFFFF )
    {
        return;
    }

    if ( m_duty == 0 )
    {
        disablePwm( m_pin );
        return;
    }

    frequency = (1000000/m_microseconds);
    analogWriteFrequency(m_pin,  frequency);
    pwm_start(  m_pin,   
                TIMER1_PWM_MAX_DUTY, 
                m_duty,   1 );
}


void TimerOne::disablePwm(char pin) 
{
    if( (pin == TIMER1_A_PIN)
     || (pin == TIMER1_B_PIN) )
    {
        pwm_stop( pin );
    }
}
#endif



