/* 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) 2022. 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 "ac780x_pwm_reg.h"
#include "string.h"

/* ============================================  Define  ============================================ */
#define ENCODER_LINES                   36                          /*!<编码器线数 */
#define PULSE_PER_REVOLUTION            (ENCODER_LINES << 2)        /*!<编码器每转一圈输出的脉冲数 */

/* ===========================================  Typedef  ============================================ */
typedef enum
{
    ENCODER_DIR_FORWARD = 0,  /*!< Phase input signal is not inverted */
    ENCODER_DIR_REVERSE,      /*!< Phase input signal is inverted */
} Encoder_Dir_Type;

/* ==========================================  Variables  =========================================== */
uint16_t g_encoderCnt = 0;                                  /*<!*编码器位置脉冲数*/
int16_t  g_encoderCircleCnt = 0;                            /*<!编码器旋转圈数计数*/
Encoder_Dir_Type  g_encoderDir = ENCODER_DIR_FORWARD;       /*<!编码器旋转方向*/
/* ====================================  Functions declaration  ===================================== */


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

/*!
 * @brief   PWM1_Decode_CallBack
 *          PWM1模块中断回调函数
 * @param   wpara: 溢出中断标志参数
 *          lpara：通道中断标志参数
 * @return  none
 */
void PWM1_Decode_CallBack(void *device, uint32_t wpara, uint32_t lpara)
{

    if (0 != wpara) /*溢出中断*/
    {
        if (0 == PWM_GetQuadOverflowDir(PWM1))/*读取正交解码计数方向*/
        {
            g_encoderDir = ENCODER_DIR_REVERSE;
            g_encoderCircleCnt--;
        }
        else
        {
            g_encoderDir = ENCODER_DIR_FORWARD;
            g_encoderCircleCnt++;
        }
    }
    if (0 != (lpara & PWM_STR_CH0SF_Msk)) /*通道中断*/
    {

    }

}

/*!
 * @brief   PWM1_QuadDecode_Init
 *          PWM1模块初始化，配置正交解码模式，PWM1_CH0:A相输入，PWM1_CH1:B相输入
 * @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(GPIOB, GPIO_PIN0, GPIO_FUN2);  /* PB0--PWM1_CH1.该引脚只在32pin封装上有 */
    GPIO_SetFunc(GPIOB, GPIO_PIN1, GPIO_FUN2);  /* PB1--PWM1_CH0,该引脚只在32pin封装上有.*/

    GPIO_SetPullup(GPIOB, GPIO_PIN0, ENABLE); /*使能上拉*/
    GPIO_SetPullup(GPIOB, GPIO_PIN1, ENABLE); /*使能上拉*/


    /*通道配置*/
    quadPhaseAConfig.polarity = PWM_QUAD_PHASE_NORMAL;  /*A相输入极性为正常极性。*/
    quadPhaseAConfig.filterEn = DISABLE;                /*A相滤波器去能*/
    quadPhaseAConfig.filterVal = 0;                     /*滤波值*/
    quadPhaseBConfig.polarity = PWM_QUAD_PHASE_NORMAL;  /*B相输入极性为正常极性。*/
    quadPhaseBConfig.filterEn = DISABLE;                /*B相滤波器去能*/
    quadPhaseBConfig.filterVal = 0;                     /*滤波值*/
    quadDecodeConfig.mode = PWM_QUAD_PHASE_ENCODE;      /*A相和B相编码模式*/
    quadDecodeConfig.phaseAConfig = quadPhaseAConfig;   /*A相配置赋值*/
    quadDecodeConfig.phaseBConfig = quadPhaseBConfig;   /*B相配置赋值*/
    quadDecodeConfig.quadEn = ENABLE;                   /*正交解码使能*/

    /*PWM模块配置*/
    config.mode = PWM_MODE_QUADRATURE_DECODER;          /*PWM模块配置为正交解码模式*/
    config.initModeStruct = &quadDecodeConfig;          /*正交解码配置赋值*/
    config.clkSource = PWM_CLK_SOURCE_APB;              /*PWM时钟源配置*/
    config.clkPsc = 0;                                  /*PWM时钟源分频*/
    config.initValue = 0;                               /*计数器初始寄存器值*/
    config.maxValue = PULSE_PER_REVOLUTION - 1;         /*PWM计数器最大值，为编码器线数，即编码器转一圈发出的脉冲数*/
    config.overflowInterrupEn = ENABLE;                 /*计数器溢出中断使能*/
    config.cntOverflowFreq = 0;                         /*CNTOF中断产生的频率与计数器频率的关系(0-127), 0表示每次计数器溢出都产生溢出中断，1表示间隔1次，2表示间隔2次，以此类推。*/
    config.interruptEn = ENABLE;                        /*PWM中断使能*/
    config.callBack = PWM1_Decode_CallBack;             /*PWM中断回调*/
    PWM_Init(PWM1, &config);                            /*配置初始化生效*/


}

/*!
 * @brief   GetEncoderCnt
 *          获取编码器脉冲计数
 * @param   none
 * @return  none
 */
void GetEncoderCnt(void)
{
    g_encoderCnt = PWM1->CNT & 0xFFFF;   /*获取编码器脉冲计数*/
}

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