/* Copyright Statement:
 *
 * This software/firmware and related documentation ("AutoChips Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to AutoChips Inc. and/or its licensors. Without
 * the prior written permission of AutoChips inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of AutoChips Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * AutoChips Inc. (C) 2023. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("AUTOCHIPS SOFTWARE")
 * RECEIVED FROM AUTOCHIPS AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. AUTOCHIPS EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES AUTOCHIPS PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE AUTOCHIPS SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN AUTOCHIPS
 * SOFTWARE. AUTOCHIPS SHALL ALSO NOT BE RESPONSIBLE FOR ANY AUTOCHIPS SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AUTOCHIPS'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE AUTOCHIPS SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT AUTOCHIPS'S OPTION, TO REVISE OR REPLACE THE
 * AUTOCHIPS SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO AUTOCHIPS FOR SUCH AUTOCHIPS SOFTWARE AT ISSUE.
 */
/******************************************************************************
 * @version: V1.0.0 demo
 ******************************************************************************/

/*!
* @file pwm.c
*
* @brief This file contains the user pwm function..
*
*/

/* ===========================================  Includes  =========================================== */

#include "pwm.h"
#include "ac780x_gpio.h"
#include <string.h>

/* ============================================  Define  ============================================ */

#define ENCODER_LINES                   36                          /* Encoder line number */
#define PULSE_PER_REVOLUTION            (ENCODER_LINES << 2)        /* Pulse per cycle */

/* ===========================================  Typedef  ============================================ */

/* ==========================================  Variables  =========================================== */

uint16_t g_encoderCnt = 0;                                  /* encoder paulse Cnt */
int16_t  g_encoderCircleCnt = 0;                            /* encoder circle count */
Encoder_Dir_Type  g_encoderDir = ENCODER_DIR_FORWARD;       /* encoder turn direction */

/* ====================================  Functions declaration  ===================================== */

/* ======================================  Functions define  ======================================== */

/*!
 * @brief PWM1_Callback
 *        PWM1 interrupts user callback function
 *
 * @param[in] wpara: Overflow interrupt flag parameter
 *
 * @param[in] lpara: Channel matching interrupt flag parameter
 *
 * @return none
 */
void PWM1_Decode_CallBack(void *device, uint32_t wpara, uint32_t lpara)
{
    if (wpara & PWM_INIT_CNTOF_Msk) /* Overflow interrupt determination */
    {
        if (0 == PWM_GetQuadOverflowDir(PWM1))  /* Get cross dir in overflow moment */
        {
            g_encoderDir = ENCODER_DIR_REVERSE;
            g_encoderCircleCnt--;
        }
        else
        {
            g_encoderDir = ENCODER_DIR_FORWARD;
            g_encoderCircleCnt++;
        }
    }
}

/*!
 * @brief   PWM1_QuadDecode_Init
 *          PWM1 module initialization, configuration of quadrature decoding mode, PWM1_CH0: A-phase input, PWM1_CH1: B-phase input.
 * @param   none
 *
 * @return  none
 */
void PWM1_QuadDecode_Init(void)
{
    PWM_ConfigType config;
    PWM_QuadDecodeConfigType quadDecodeConfig;
    PWM_QuadPhaseConfigType quadPhaseAConfig, quadPhaseBConfig;

    memset(&config, 0U, sizeof(config));
    memset(&quadDecodeConfig, 0U, sizeof(quadDecodeConfig));
    memset(&quadPhaseAConfig, 0U, sizeof(quadPhaseAConfig));
    memset(&quadPhaseBConfig, 0U, sizeof(quadPhaseBConfig));

    GPIO_SetFunc(GPIOC, GPIO_PIN7, GPIO_FUN5);  /* PC7  PWM1_CH1 */
    GPIO_SetFunc(GPIOC, GPIO_PIN6, GPIO_FUN5);  /* PC6  PWM1_CH0 */

    GPIO_SetPullup(GPIOC, GPIO_PIN7, ENABLE);   /* Enable pull-up */
    GPIO_SetPullup(GPIOC, GPIO_PIN6, ENABLE);   /* Enable pull-up */

    quadPhaseAConfig.polarity = PWM_QUAD_PHASE_NORMAL;  /* quadrature A phase polarity */
    quadPhaseAConfig.filterEn = DISABLE;                /* Filter Enable */
    quadPhaseAConfig.filterVal = 0;                     /* Filter value */

    quadPhaseBConfig.polarity = PWM_QUAD_PHASE_NORMAL;  /* quadrature B phase polarity */
    quadPhaseBConfig.filterEn = DISABLE;                /* Filter Enable */
    quadPhaseBConfig.filterVal = 0;                     /* Filter value */

    quadDecodeConfig.mode = PWM_QUAD_PHASE_ENCODE;      /* quadrature decode mode */
    quadDecodeConfig.phaseAConfig = quadPhaseAConfig;   /* PhaseA config */
    quadDecodeConfig.phaseBConfig = quadPhaseBConfig;   /* PhaseB config */
    quadDecodeConfig.quadEn = ENABLE;                   /* Enable quadrature decode mode */

    config.mode = PWM_MODE_QUADRATURE_DECODER;          /* PWM mode configuration */
    config.initModeStruct = &quadDecodeConfig;          /* Different modes initialize configuration struct assignments accordingly */
    config.clkSource = PWM_CLK_SOURCE_APB;              /* PWM clock source selection */
    config.clkPsc = 0;                                  /* Clock division factor */
    config.initValue = 0;                               /* Initial count value */
    config.maxValue = PULSE_PER_REVOLUTION - 1;         /* Maximum count value. Determines the output waveform frequency */
    config.overflowInterrupEn = ENABLE;                 /* Overflow interrupts the enable bit */
    config.cntOverflowFreq = 0;                         /* The frequency at which overflow interrupts are generated, 0 means that each overflow produces an interrupt */
    config.interruptEn = ENABLE;                        /* PWM total interrupt enable bit */
    config.callback = PWM1_Decode_CallBack;             /* PWM interrupts user callback function */

    PWM_Init(PWM1, &config);
}

/*!
* @brief Get pulse count captured by PWM module.
*
* @param[in] none
*
* @return none
*/
void GetEncoderCnt(void)
{
    g_encoderCnt = PWM_GetCounter(PWM1);
}

/* =============================================  EOF  ============================================== */
