/* 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  ============================================ */

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


/* ==========================================  Variables  =========================================== */
uint16_t g_low_over_cnt = 0;      /*<!低电平溢出次数*/
uint16_t g_high_over_cnt = 0;     /*<!高电平溢出次数*/
uint32_t g_low_time = 0;          /*<!低电平总计数值*/
uint32_t g_high_time = 0;         /*<!高电平总计数值*/
uint16_t g_captureFreq = 0;       /*<!PWM频率*/
uint16_t g_captrueDuty = 0;       /*<!PWM占空比*/
/* ====================================  Functions declaration  ===================================== */


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

/*!
 * @brief   PWM2_Callback
 *          PWM2模块中断回调函数
 * @param   wpara: 溢出中断标志参数
 *          lpara：通道中断标志参数
 * @return  none
 */
void PWM2_Callback(void *device, uint32_t wpara, uint32_t lpara)
{
    uint16_t captureValueCH2 = 0;
    uint16_t captureValueCH3 = 0;

    if (0 != wpara) /*溢出中断*/
    {
        if (GPIO_GetPinLevel(GPIOA, GPIO_PIN1) == GPIO_LEVEL_LOW) /*若上次状态为低电平，那么将溢出次数加到低电平上。若上次状态为高电平，那么将溢出次数加到高电平上*/
        {
            g_low_over_cnt ++;
        }
        else
        {
            g_high_over_cnt ++;
        }
    }
    if (0 != (lpara & PWM_STR_CH3SF_Msk)) /*双边沿捕获是在2n+1通道发生捕获时才产生中断*/
    {
        captureValueCH2 = PWM_GetChannelCountValue(PWM2, PWM_CH_2); /*上升沿时捕获计数值*/
        captureValueCH3 = PWM_GetChannelCountValue(PWM2, PWM_CH_3); /*下降沿时捕获计数值并产生中断*/

        PWM2->CNT = 0;/*将计数器清零*/
        /*捕获中断后，若外部电平为低电平，则捕获到的数据为高电平计数值。若外部电平为高电平，则捕获到的数据为低电平计数值*/
        if (GPIO_GetPinLevel(GPIOA, GPIO_PIN1) == GPIO_LEVEL_LOW) /*CH3捕获中断后外部电平为低电平，才处理数据*/
        {
            g_high_time = (uint32_t)(g_high_over_cnt) * 65536 + captureValueCH3 - captureValueCH2; /*计算高电平计数值，考虑溢出次数*/
            g_low_time = (uint32_t)(g_low_over_cnt) * 65536 + captureValueCH2; /*计算低电平计数值，考虑溢出次数*/

            /*PWM频率和占空比计算*/
            g_captureFreq  = 16000000 / (0 + 1) / (g_low_time + g_high_time);
            g_captrueDuty = (g_high_time) * 100 / (g_low_time + g_high_time); /*将占空比放大100倍，方便整数计算，10为10%*/
            g_low_over_cnt = 0;
            g_high_over_cnt = 0;
        }
    }

}


/*!
 * @brief   PWM2_InputCapture_DualChannel_Init
 *          PWM2模块初始化，PWM2_CH2配置为输入捕获，使用双边沿捕获
 * @param   none
 * @return  none
 */
void PWM2_InputCapture_DualChannel_Init(void)
{
    PWM_ConfigType config;
    PWM_inputCaptureConfigType inputConfig;
    PWM_inputChConfigType inputChConfig[1];

    memset(&config, 0U, sizeof(config));
    memset(&inputConfig, 0U, sizeof(inputConfig));
    memset(&inputChConfig, 0U, sizeof(inputChConfig));

    GPIO_SetFunc(GPIOA, GPIO_PIN1, GPIO_FUN1); /* PA1--PWM2_CH2.*/

    /*双通道边沿捕获频率原理：
      CH2n设为上升沿捕获, 当CH2n捕获到上升沿时，CH2n记录当前的Count值。
      CH2n+1设为下降沿捕获，当CH2n+1捕获到下降沿时，CH2n+1记录当前的Count值,
      然后产生通道中断，基于两个通道统计的Count值，计算频率和占空比。
    */
    /*input channel config*/
    inputChConfig[0].channel = PWM_CH_2;                                /*输入通道选择 */
    inputChConfig[0].mode = PWM_INPUTCAP_DUAL_EDGE;                     /*输入捕获模式选择：PWM_INPUTCAP_SINGLE_EDGE为普通输入捕获，PWM_INPUTCAP_DUAL_EDGE为双边沿捕获 */
    inputChConfig[0].filterEn = ENABLE;                                 /*输入滤波器使能位 */
    inputChConfig[0].filterValue = 16;                                  /*滤波值 */
    inputChConfig[0].interruptEn = ENABLE;                              /*通道中断使能位 */

    /*PWM_INPUTCAP_SINGLE_EDGE模式下需要配置的参数，双边沿捕获模式下可忽略*/
    inputChConfig[0].detectType = PWM_BOTH_EDGE_DETECT;                 /*输入捕获边沿选择*/
    inputChConfig[0].eventPsc = PWM_EVENT_PSC_1;                        /*捕获比率，PWM_EVENT_PSC_1，发生一次有效边沿产生一次中断，PWM_EVENT_PSC_2，发生两次有效边沿产生一次中断 */

    /*PWM_INPUTCAP_DUAL_EDGE模式下需要配置的参数 ，普通输入捕获模式下可忽略*/
    inputChConfig[0].measureType = PWM_POSITIVE_PLUSE_WIDTH_MEASURE;    /*双边沿捕获模式的 通道测量模式*/
    inputChConfig[0].onceMode = PWM_INPUTCAP_CONTINUOUS;                /*连续模式配置 */


    /*input capture config*/
    inputConfig.channelNum = 1;                   /*输入捕获通道数目 */
    inputConfig.channelConfig = inputChConfig;    /*输入捕获通道配置赋值*/

    /*设置捕获时钟频率：
    可捕获的最小频率（前提是时钟源为PWM_CLK_SOURCE_APB）：
    min_clk = SYS_CLK/(PWM_PRES+1)/65536 = 16000000/1/65536 = 244HZ
    */
    /*pwm config*/
    config.mode = PWM_MODE_INPUT_CAPTURE;         /*PWM模式配置，PWM_MODE_INPUT_CAPTURE--PWM输入捕获模式 */
    config.initModeStruct = &inputConfig;         /*不同模式相应初始化配置结构体赋值 */
    config.clkSource = PWM_CLK_SOURCE_APB;        /*PWM时钟源选择 */
    config.clkPsc = 0;                            /*时钟分频系数 */
    config.initValue = 0;                         /*初始计数值 */
    config.maxValue = 0xffff;                     /*最大计数值，在输入模式下，设置为最大16位数据 */
    config.overflowInterrupEn = ENABLE;           /*溢出中断使能位 */
    config.cntOverflowFreq = 0;                   /*溢出中断产生的频率与计数器频率的关系，0表示每次计数器溢出都产生中断，1表示间隔一次，以此类推 */
    config.interruptEn = ENABLE;                  /*PWM总中断使能位  */
    config.callBack = PWM2_Callback;              /*中断回调函数 */

    PWM_Init(PWM2, &config);

}

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