diff --git a/vendor/others/demo/zhinenglunyi/generatecode/feature.h b/vendor/others/demo/zhinenglunyi/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..a1f9eb276a05eee970c2b38cac5d189c83d50342 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/generatecode/feature.h @@ -0,0 +1,93 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file feature.h + * @author MCU Driver Team + * @brief This file contains macro configurations related to the project. This file is generated by the IDE tool. + */ + +#ifndef McuMagicTag_FEATURE_H +#define McuMagicTag_FEATURE_H + +/* Macro definitions --------------------------------------------------------- */ +#define CHIP_3061MNPICA MACRO_ENABLE + +#define MACRO_ENABLE 1 +#define MACRO_DISABLE 0 + +/* Macro switch */ +#define BASE_DEFINE_USE_ASSERT MACRO_ENABLE +#ifndef FLASH_CRC_CONFIG +#define FLASH_CRC_CONFIG +#endif /* #ifndef FLASH_CRC_CONFIG */ +#define BASE_MATH_SINCOS_MIDDLE_TABLE MACRO_ENABLE /**< This macro is used to control the table type when the + BASE_MATH_GetSinCos() queries the table. When the value of + this macro is MACRO_ENABLE, the error value obtained by the + BASE_MATH_GetSinCos() is relatively small, and the return + value of the function may be greater than or less than the + actual value. When the value of this macro is MACRO_DISABLE, + the error value obtained by the BASE_MATH_GetSinCos() is + relatively large. However, in the range [0°, 180°) and + [180°, 360°), the return value of the function is either + greater than or less than the actual value. */ + +/* Peripheral module macro switch--------------------------------------------- */ +#define BOARD_DIM_NUM 1 /**< Number of dimming handle arrays. */ + +#define BOARD_KEY_NUM 10 /**< Number of key handle arrays. */ +#define BOARD_KEY_PRESS_ON GPIO_HIGH_LEVEL /**< GPIO status corresponding to long press valid. */ +#define BOARD_KEY_PRESS_OFF GPIO_LOW_LEVEL /**< GPIO status corresponding to short press valid. */ + +#define BOARD_LED_SEG_NUM 4 /**< Number of segments. */ +#define BOARD_LED_SEGMENT_ON GPIO_HIGH_LEVEL /**< GPIO level status corresponding to valid segments. */ +#define BOARD_LED_SEGMENT_OFF GPIO_LOW_LEVEL /**< GPIO level status corresponding to invalid segments. */ + +#define BOARD_MKEY_SCHEME_NUMBER BOARD_MKEY_SCHEME_NUMBER_ONE /**< Define the scheme to be adopted. */ +#define BOARD_MKEY_OUT_NUM 4 /**< Number of GPIO pins used as output during scanning. */ +#define BOARD_MKEY_IN_NUM 4 /**< Number of GPIO pins used as input during scanning. */ +#define BOARD_MKEY_OUT_PIN_VALID GPIO_LOW_LEVEL /**< GPIO level status corresponding to the valid \ + status of the output GPIO in the key matrix. */ +#define BOARD_MKEY_OUT_PIN_INVALID GPIO_HIGH_LEVEL /**< GPIO level status corresponding to the \ + invalid status of the output GPIO in the key matrix. */ +#define BOARD_MKEY_IN_PIN_VALID GPIO_LOW_LEVEL /**< Indicates the GPIO level corresponding to the \ + valid status of the input GPIO in the key matrix. */ +#define BOARD_MKEY_IN_PIN_INVALID GPIO_HIGH_LEVEL /**< Indicates the GPIO level corresponding to the \ + invalid status of the input GPIO in the key matrix. */ + +#define BOARD_PULSES_NUM 2 /**< Number of pulse handles. */ + +#define BASE_DEFINE_SLIPAVERAGE_NUM 2 /**< Sliding average array length. */ + +#define LISTNODE_MAX 20 + +#define BASE_DEFINE_DMA_QUICKSTART + +#define XTRAIL_FREQ 30000000U + +#define DBG_USE_NO_PRINTF 0U +#define DBG_USE_UART_PRINTF 1U + +#define DBG_PRINTF_USE DBG_USE_UART_PRINTF +#if (DBG_PRINTF_USE == DBG_USE_UART_PRINTF) +#define DBG_PRINTF_UART_PORT UART0 +#endif + +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* USER CODE END 0 */ + +#endif /* McuMagicTag_FEATURE_H */ \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/generatecode/main.h b/vendor/others/demo/zhinenglunyi/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..935136b62ec97499142eaa640b3ddb4350edfd47 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/generatecode/main.h @@ -0,0 +1,101 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file main.h + * @author MCU Driver Team + * @brief This file contains driver init functions. + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_SYSTEM_INIT_H +#define McuMagicTag_SYSTEM_INIT_H + +#include "adc.h" +#include "adc_ex.h" +#include "acmp.h" +#include "acmp_ex.h" +#include "apt.h" +#include "uart.h" +#include "uart_ex.h" +#include "gpio.h" +#include "timer.h" +#include "timer_ex.h" +#include "pga.h" +#include "crg.h" +#include "dma.h" +#include "dma_ex.h" +#include "iocmg.h" + +#define IO_SPEED_FAST 0x00U +#define IO_SPEED_SLOW 0x01U + +#define IO_DRV_LEVEL4 0x00U +#define IO_DRV_LEVEL3 0x01U +#define IO_DRV_LEVEL2 0x02U +#define IO_DRV_LEVEL1 0x03U + +#define XTAL_DRV_LEVEL4 0x03U +#define XTAL_DRV_LEVEL3 0x02U +#define XTAL_DRV_LEVEL2 0x01U +#define XTAL_DRV_LEVEL1 0x00U + +#define GpioStartStop_PIN GPIO_PIN_4 +#define GpioStartStop_HANDLE g_gpio2 + +extern ACMP_Handle g_acmp0; +extern PGA_Handle g_pga0; +extern PGA_Handle g_pga1; +extern TIMER_Handle g_timer0; +extern TIMER_Handle g_timer1; +extern UART_Handle g_uart0; +extern APT_Handle g_apt0; +extern APT_Handle g_apt1; +extern APT_Handle g_apt2; +extern ADC_Handle g_adc0; + +extern DMA_Handle g_dmac; + +extern GPIO_Handle g_gpio2; +extern GPIO_Handle g_gpio1; +extern GPIO_Handle g_gpio4; +extern GPIO_Handle g_gpio5; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void UART0WriteInterruptCallback(void *handle); +void UART0ReadInterruptCallback(void *handle); + +void UART0InterruptErrorCallback(void *handle); +void MotorStatemachineCallBack(void *handle); +void TIMER1_DMAOverFlow_InterruptProcess(void *handle); +void CheckPotentiometerValueCallback(void *handle); +void TIMER0_DMAOverFlow_InterruptProcess(void *handle); +void MotorCarrierProcessCallback(void *aptHandle); +void MotorSysErrCallback(void *aptHandle); + +void UART0_TXDMACallback(void *handle); + +void MotorStartStopKeyCallback(void *param); +void GPIO2_1_CallbackFunc(void *param); +void GPIO5_0_CallbackFunc(void *param); + +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* USER CODE END 0 */ + +#endif /* McuMagicTag_SYSTEM_INIT_H */ \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/generatecode/system_init.c b/vendor/others/demo/zhinenglunyi/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..5316f78a618598dea3f78829e6d2e6543e542add --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/generatecode/system_init.c @@ -0,0 +1,751 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file system_init.c + * @author MCU Driver Team + * @brief This file contains driver init functions. + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAND_RATE 1843200 + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect) +{ + CRG_Handle crg; + crg.baseAddress = CRG; + crg.pllRefClkSelect = CRG_PLL_REF_CLK_SELECT_HOSC; + crg.pllPreDiv = CRG_PLL_PREDIV_4; + crg.pllFbDiv = 48; /* PLL Multiplier 48 */ + crg.pllPostDiv = CRG_PLL_POSTDIV_2; + crg.coreClkSelect = CRG_CORE_CLK_SELECT_PLL; + crg.handleEx.pllPostDiv2 = CRG_PLL_POSTDIV2_3; + crg.handleEx.clk1MSelect = CRG_1M_CLK_SELECT_HOSC; + crg.handleEx.clk1MDiv = (25 - 1); /* The 1 MHz freq is equal to the input clock frequency / (clk_1m_div + 1). 25 is the div of the clk_1m in CLOCK. */ + + if (HAL_CRG_Init(&crg) != BASE_STATUS_OK) { + return BASE_STATUS_ERROR; + } + *coreClkSelect = crg.coreClkSelect; + return BASE_STATUS_OK; +} + +static void DMA_Channel0Init(void *handle) +{ + DMA_ChannelParam dma_param; + dma_param.direction = DMA_MEMORY_TO_PERIPH_BY_DMAC; + dma_param.srcAddrInc = DMA_ADDR_INCREASE; + dma_param.destAddrInc = DMA_ADDR_UNALTERED; + dma_param.srcPeriph = DMA_REQUEST_MEM; + dma_param.destPeriph = DMA_REQUEST_UART0_TX; + dma_param.srcWidth = DMA_TRANSWIDTH_BYTE; + dma_param.destWidth = DMA_TRANSWIDTH_BYTE; + dma_param.srcBurst = DMA_BURST_LENGTH_1; + dma_param.destBurst = DMA_BURST_LENGTH_1; + dma_param.pHandle = handle; + HAL_DMA_InitChannel(&g_dmac, &dma_param, DMA_CHANNEL_ZERO); +} + +static void DMA_Init(void) +{ + HAL_CRG_IpEnableSet(DMA_BASE, IP_CLK_ENABLE); + g_dmac.baseAddress = DMA; + IRQ_Register(IRQ_DMA_TC, HAL_DMA_IrqHandlerTc, &g_dmac); + IRQ_Register(IRQ_DMA_ERR, HAL_DMA_IrqHandlerError, &g_dmac); + IRQ_EnableN(IRQ_DMA_TC); + IRQ_EnableN(IRQ_DMA_ERR); + HAL_DMA_Init(&g_dmac); + DMA_Channel0Init((void *)(&g_uart0)); + HAL_DMA_SetChannelPriorityEx(&g_dmac, DMA_CHANNEL_ZERO, DMA_PRIORITY_HIGHEST); +} + +static void ACMP0_Init(void) +{ + HAL_CRG_IpEnableSet(ACMP0_BASE, IP_CLK_ENABLE); /* ACMP clock bit reset. */ + g_acmp0.baseAddress = ACMP0_BASE; + g_acmp0.inOutConfig.inputNNum = ACMP_INPUT_N_SELECT2; + g_acmp0.inOutConfig.inputPNum = ACMP_INPUT_P_SELECT2; + g_acmp0.inOutConfig.polarity = ACMP_OUT_NOT_INVERT; + g_acmp0.filterCtrl.filterMode = ACMP_FILTER_NONE; + g_acmp0.hysteresisVol = ACMP_HYS_VOL_30MV; + g_acmp0.interruptEn = BASE_CFG_UNSET; + HAL_ACMP_Init(&g_acmp0); +} + +static void ADC0_Init(void) +{ + HAL_CRG_IpEnableSet(ADC0_BASE, IP_CLK_ENABLE); + HAL_CRG_IpClkSelectSet(ADC0_BASE, CRG_ADC_CLK_ASYN_PLL_DIV); + HAL_CRG_IpClkDivSet(ADC0_BASE, CRG_ADC_DIV_1); + + g_adc0.baseAddress = ADC0; + g_adc0.socPriority = ADC_PRIMODE_ALL_ROUND; + + HAL_ADC_Init(&g_adc0); + + SOC_Param socParam = {0}; + socParam.adcInput = ADC_CH_ADCINA0; /* PGA0_OUT(ADC AIN0) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_22CLK; /* adc sample total time 22 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_APT0_SOCA; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM1, &socParam); + + socParam.adcInput = ADC_CH_ADCINA1; /* PGA1_OUT(ADC AIN1) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_22CLK; /* adc sample total time 22 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_APT0_SOCA; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM6, &socParam); + + socParam.adcInput = ADC_CH_ADCINA9; /* PIN7(ADC AIN9) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_22CLK; /* adc sample total time 22 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM0, &socParam); + + socParam.adcInput = ADC_CH_ADCINA5; /* PIN2(ADC AIN5) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_22CLK; /* adc sample total time 22 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM3, &socParam); + + socParam.adcInput = ADC_CH_ADCINA15; /* PIN14(ADC AIN15) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_22CLK; /* adc sample total time 22 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM4, &socParam); +} + +__weak void MotorSysErrCallback(void *aptHandle) +{ + BASE_FUNC_UNUSED(aptHandle); + /* USER CODE BEGIN APT0_EVENT_INTERRUPT */ + /* USER CODE END APT0_EVENT_INTERRUPT */ +} + +__weak void MotorCarrierProcessCallback(void *aptHandle) +{ + BASE_FUNC_UNUSED(aptHandle); + /* USER CODE BEGIN APT0_TIMER_INTERRUPT */ + /* USER CODE END APT0_TIMER_INTERRUPT */ +} + +static void APT0_ProtectInit(void) +{ + APT_OutCtrlProtectEx protectApt = {0}; + protectApt.ocEventEnEx = BASE_CFG_ENABLE; + protectApt.ocEventModeEx = APT_OUT_CTRL_ONE_SHOT; + protectApt.ocActionEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocActionBEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocEvtInterruptEnEx = BASE_CFG_ENABLE; + protectApt.ocSysEvent = APT_SYS_EVT_DEBUG | APT_SYS_EVT_CLK | APT_SYS_EVT_MEM; + protectApt.originalEvtEx = APT_EM_ORIGINAL_SRC_ACMP0; + protectApt.evtPolarityMaskEx = APT_EM_ACMP0_INVERT_BIT; + protectApt.filterCycleNumEx = 0; + HAL_APT_ProtectInitEx(&g_apt0, &protectApt); +} + +static void APT0_Init(void) +{ + HAL_CRG_IpEnableSet(APT0_BASE, IP_CLK_ENABLE); + + g_apt0.baseAddress = APT0; + + /* Clock Settings */ + g_apt0.waveform.dividerFactor = 1 - 1; + /* Timer Settings */ + g_apt0.waveform.timerPeriod = 7500; /* 7500 is count period of APT time-base timer */ + g_apt0.waveform.cntMode = APT_COUNT_MODE_UP_DOWN; + + /* Wave Form */ + g_apt0.waveform.basicType = APT_PWM_BASIC_A_HIGH_B_LOW; + g_apt0.waveform.chAOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt0.waveform.chBOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt0.waveform.divInitVal = 0; + g_apt0.waveform.cntInitVal = 0; + g_apt0.waveform.cntCmpLeftEdge = 500; /* 500 is count compare point of the left edge of PWM waveform */ + g_apt0.waveform.cntCmpRightEdge = 4000; /* 4000 is count compare point of the right edge of PWM waveform */ + g_apt0.waveform.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt0.waveform.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + g_apt0.waveform.deadBandCnt = 225; /* 225 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt0.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt0.adcTrg.cntCmpSOCA = 375; /* 375 is count compare point of ADC trigger source SOCA when using CMPA */ + g_apt0.adcTrg.trgSrcSOCA = APT_CS_SRC_CNTR_CMPA_DOWN; + g_apt0.adcTrg.trgScaleSOCA = 1; + + /* ADC Trigger SOCB */ + g_apt0.adcTrg.trgEnSOCB = BASE_CFG_ENABLE; + g_apt0.adcTrg.cntCmpSOCB = 1; + g_apt0.adcTrg.trgSrcSOCB = APT_CS_SRC_CNTR_CMPB_DOWN; + g_apt0.adcTrg.trgScaleSOCB = 1; + + g_apt0.adcTrg.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt0.adcTrg.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + + /* Timer Trigger */ + g_apt0.tmrInterrupt.tmrInterruptEn = BASE_CFG_ENABLE; + g_apt0.tmrInterrupt.tmrInterruptSrc = APT_INT_SRC_CNTR_ZERO; + g_apt0.tmrInterrupt.tmrInterruptScale = 1; + + APT0_ProtectInit(); + + HAL_APT_PWMInit(&g_apt0); + HAL_APT_RegisterCallBack(&g_apt0, APT_EVENT_INTERRUPT, MotorSysErrCallback); + IRQ_SetPriority(IRQ_APT0_EVT, 7); /* 7 is priority value */ + IRQ_Register(IRQ_APT0_EVT, HAL_APT_EventIrqHandler, &g_apt0); + IRQ_EnableN(IRQ_APT0_EVT); + HAL_APT_RegisterCallBack(&g_apt0, APT_TIMER_INTERRUPT, MotorCarrierProcessCallback); + IRQ_SetPriority(IRQ_APT0_TMR, 5); /* 5 is priority value */ + IRQ_Register(IRQ_APT0_TMR, HAL_APT_TimerIrqHandler, &g_apt0); + IRQ_EnableN(IRQ_APT0_TMR); +} + +static void APT1_ProtectInit(void) +{ + APT_OutCtrlProtectEx protectApt = {0}; + protectApt.ocEventEnEx = BASE_CFG_ENABLE; + protectApt.ocEventModeEx = APT_OUT_CTRL_ONE_SHOT; + protectApt.ocActionEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocActionBEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocEvtInterruptEnEx = BASE_CFG_DISABLE; + protectApt.ocSysEvent = APT_SYS_EVT_DEBUG | APT_SYS_EVT_CLK | APT_SYS_EVT_MEM; + protectApt.originalEvtEx = APT_EM_ORIGINAL_SRC_ACMP0; + protectApt.evtPolarityMaskEx = APT_EM_ACMP0_INVERT_BIT; + protectApt.filterCycleNumEx = 0; + HAL_APT_ProtectInitEx(&g_apt1, &protectApt); +} + +static void APT1_Init(void) +{ + HAL_CRG_IpEnableSet(APT1_BASE, IP_CLK_ENABLE); + + g_apt1.baseAddress = APT1; + + /* Clock Settings */ + g_apt1.waveform.dividerFactor = 1 - 1; + /* Timer Settings */ + g_apt1.waveform.timerPeriod = 7500; /* 7500 is count period of APT time-base timer */ + g_apt1.waveform.cntMode = APT_COUNT_MODE_UP_DOWN; + + /* Wave Form */ + g_apt1.waveform.basicType = APT_PWM_BASIC_A_HIGH_B_LOW; + g_apt1.waveform.chAOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt1.waveform.chBOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt1.waveform.divInitVal = 0; + g_apt1.waveform.cntInitVal = 0; + g_apt1.waveform.cntCmpLeftEdge = 500; /* 500 is count compare point of the left edge of PWM waveform */ + g_apt1.waveform.cntCmpRightEdge = 4000; /* 4000 is count compare point of the right edge of PWM waveform */ + g_apt1.waveform.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt1.waveform.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + g_apt1.waveform.deadBandCnt = 225; /* 225 is dead-band value */ + + APT1_ProtectInit(); + + HAL_APT_PWMInit(&g_apt1); +} + +static void APT2_ProtectInit(void) +{ + APT_OutCtrlProtectEx protectApt = {0}; + protectApt.ocEventEnEx = BASE_CFG_ENABLE; + protectApt.ocEventModeEx = APT_OUT_CTRL_ONE_SHOT; + protectApt.ocActionEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocActionBEx = APT_OUT_CTRL_ACTION_LOW; + protectApt.ocEvtInterruptEnEx = BASE_CFG_DISABLE; + protectApt.ocSysEvent = APT_SYS_EVT_DEBUG | APT_SYS_EVT_CLK | APT_SYS_EVT_MEM; + protectApt.originalEvtEx = APT_EM_ORIGINAL_SRC_ACMP0; + protectApt.evtPolarityMaskEx = APT_EM_ACMP0_INVERT_BIT; + protectApt.filterCycleNumEx = 0; + HAL_APT_ProtectInitEx(&g_apt2, &protectApt); +} + +static void APT2_Init(void) +{ + HAL_CRG_IpEnableSet(APT2_BASE, IP_CLK_ENABLE); + + g_apt2.baseAddress = APT2; + + /* Clock Settings */ + g_apt2.waveform.dividerFactor = 1 - 1; + /* Timer Settings */ + g_apt2.waveform.timerPeriod = 7500; /* 7500 is count period of APT time-base timer */ + g_apt2.waveform.cntMode = APT_COUNT_MODE_UP_DOWN; + + /* Wave Form */ + g_apt2.waveform.basicType = APT_PWM_BASIC_A_HIGH_B_LOW; + g_apt2.waveform.chAOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt2.waveform.chBOutType = APT_PWM_OUT_BASIC_TYPE; + g_apt2.waveform.divInitVal = 0; + g_apt2.waveform.cntInitVal = 0; + g_apt2.waveform.cntCmpLeftEdge = 500; /* 500 is count compare point of the left edge of PWM waveform */ + g_apt2.waveform.cntCmpRightEdge = 4000; /* 4000 is count compare point of the right edge of PWM waveform */ + g_apt2.waveform.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt2.waveform.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + g_apt2.waveform.deadBandCnt = 225; /* 225 is dead-band value */ + + APT2_ProtectInit(); + + HAL_APT_PWMInit(&g_apt2); +} + +__weak void MotorStartStopKeyCallback(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + BASE_FUNC_UNUSED(handle); +} +__weak void GPIO2_1_CallbackFunc(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + BASE_FUNC_UNUSED(handle); +} +__weak void GPIO5_0_CallbackFunc(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + BASE_FUNC_UNUSED(handle); +} + +static void GPIO_Init(void) +{ + HAL_CRG_IpEnableSet(GPIO2_BASE, IP_CLK_ENABLE); + g_gpio2.baseAddress = GPIO2; + + g_gpio2.pins = GPIO_PIN_3; + HAL_GPIO_Init(&g_gpio2); + HAL_GPIO_SetDirection(&g_gpio2, g_gpio2.pins, GPIO_OUTPUT_MODE); + HAL_GPIO_SetValue(&g_gpio2, g_gpio2.pins, GPIO_HIGH_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_NONE); + + g_gpio2.pins = GPIO_PIN_4; + HAL_GPIO_Init(&g_gpio2); + HAL_GPIO_SetDirection(&g_gpio2, g_gpio2.pins, GPIO_INPUT_MODE); + HAL_GPIO_SetValue(&g_gpio2, g_gpio2.pins, GPIO_HIGH_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_LOW_LEVEL); + + g_gpio2.pins = GPIO_PIN_0; + HAL_GPIO_Init(&g_gpio2); + HAL_GPIO_SetDirection(&g_gpio2, g_gpio2.pins, GPIO_INPUT_MODE); + HAL_GPIO_SetValue(&g_gpio2, g_gpio2.pins, GPIO_LOW_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_NONE); + + g_gpio2.pins = GPIO_PIN_1; + HAL_GPIO_Init(&g_gpio2); + HAL_GPIO_SetDirection(&g_gpio2, g_gpio2.pins, GPIO_INPUT_MODE); + HAL_GPIO_SetValue(&g_gpio2, g_gpio2.pins, GPIO_HIGH_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_FALL_EDGE); + + HAL_CRG_IpEnableSet(GPIO1_BASE, IP_CLK_ENABLE); + g_gpio1.baseAddress = GPIO1; + + g_gpio1.pins = GPIO_PIN_0; + HAL_GPIO_Init(&g_gpio1); + HAL_GPIO_SetDirection(&g_gpio1, g_gpio1.pins, GPIO_OUTPUT_MODE); + HAL_GPIO_SetValue(&g_gpio1, g_gpio1.pins, GPIO_HIGH_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio1, g_gpio1.pins, GPIO_INT_TYPE_NONE); + + HAL_CRG_IpEnableSet(GPIO4_BASE, IP_CLK_ENABLE); + g_gpio4.baseAddress = GPIO4; + + g_gpio4.pins = GPIO_PIN_4 | GPIO_PIN_3; + HAL_GPIO_Init(&g_gpio4); + HAL_GPIO_SetDirection(&g_gpio4, g_gpio4.pins, GPIO_INPUT_MODE); + HAL_GPIO_SetValue(&g_gpio4, g_gpio4.pins, GPIO_LOW_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio4, g_gpio4.pins, GPIO_INT_TYPE_NONE); + + HAL_CRG_IpEnableSet(GPIO5_BASE, IP_CLK_ENABLE); + g_gpio5.baseAddress = GPIO5; + + g_gpio5.pins = GPIO_PIN_0; + HAL_GPIO_Init(&g_gpio5); + HAL_GPIO_SetDirection(&g_gpio5, g_gpio5.pins, GPIO_INPUT_MODE); + HAL_GPIO_SetValue(&g_gpio5, g_gpio5.pins, GPIO_HIGH_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio5, g_gpio5.pins, GPIO_INT_TYPE_FALL_EDGE); + + HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_1, GPIO2_1_CallbackFunc); + HAL_GPIO_RegisterCallBack(&g_gpio5, GPIO_PIN_0, GPIO5_0_CallbackFunc); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 2); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_Register(IRQ_GPIO5, HAL_GPIO_IrqHandler, &g_gpio5); + IRQ_SetPriority(IRQ_GPIO5, 2); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* gpio interrupt enable */ + IRQ_EnableN(IRQ_GPIO5); /* gpio interrupt enable */ + + return; +} + +static void PGA0_Init(void) +{ + HAL_CRG_IpEnableSet(PGA0_BASE, IP_CLK_ENABLE); + + g_pga0.baseAddress = PGA0_BASE; + g_pga0.externalResistorMode = BASE_CFG_ENABLE; + g_pga0.handleEx.extCapCompensation = PGA_EXT_COMPENSATION_2X; + HAL_PGA_Init(&g_pga0); +} + +static void PGA1_Init(void) +{ + HAL_CRG_IpEnableSet(PGA1_BASE, IP_CLK_ENABLE); + + g_pga1.baseAddress = PGA1_BASE; + g_pga1.externalResistorMode = BASE_CFG_ENABLE; + g_pga1.handleEx.extCapCompensation = PGA_EXT_COMPENSATION_2X; + HAL_PGA_Init(&g_pga1); +} + +__weak void CheckPotentiometerValueCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN CheckPotentiometerValueCallback */ + /* USER CODE END CheckPotentiometerValueCallback */ +} + +static void TIMER0_Init(void) +{ + HAL_CRG_IpEnableSet(TIMER0_BASE, IP_CLK_ENABLE); /* TIMER0 clock enable. */ + unsigned int load = (HAL_CRG_GetIpFreq((void *)TIMER0) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 1000000; + + g_timer0.baseAddress = TIMER0; + g_timer0.load = load - 1; /* Set timer value immediately */ + g_timer0.bgLoad = load - 1; /* Set timer value */ + g_timer0.mode = TIMER_MODE_RUN_PERIODIC; /* Run in period mode */ + g_timer0.prescaler = TIMERPRESCALER_NO_DIV; /* Don't frequency division */ + g_timer0.size = TIMER_SIZE_32BIT; /* 1 for 32bit, 0 for 16bit */ + g_timer0.interruptEn = BASE_CFG_ENABLE; + g_timer0.adcSocReqEnable = BASE_CFG_DISABLE; + g_timer0.dmaReqEnable = BASE_CFG_DISABLE; + HAL_TIMER_Init(&g_timer0); + IRQ_Register(IRQ_TIMER0, HAL_TIMER_IrqHandler, &g_timer0); + + HAL_TIMER_RegisterCallback(&g_timer0, TIMER_PERIOD_FIN, CheckPotentiometerValueCallback); + IRQ_SetPriority(IRQ_TIMER0, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_TIMER0); +} + +__weak void MotorStatemachineCallBack(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN MotorStatemachineCallBack */ + /* USER CODE END MotorStatemachineCallBack */ +} + +static void TIMER1_Init(void) +{ + HAL_CRG_IpEnableSet(TIMER1_BASE, IP_CLK_ENABLE); /* TIMER1 clock enable. */ + unsigned int load = (HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = load - 1; /* Set timer value immediately */ + g_timer1.bgLoad = load - 1; /* Set timer value */ + g_timer1.mode = TIMER_MODE_RUN_PERIODIC; /* Run in period mode */ + g_timer1.prescaler = TIMERPRESCALER_NO_DIV; /* Don't frequency division */ + g_timer1.size = TIMER_SIZE_32BIT; /* 1 for 32bit, 0 for 16bit */ + g_timer1.interruptEn = BASE_CFG_ENABLE; + g_timer1.adcSocReqEnable = BASE_CFG_DISABLE; + g_timer1.dmaReqEnable = BASE_CFG_DISABLE; + HAL_TIMER_Init(&g_timer1); + IRQ_Register(IRQ_TIMER1, HAL_TIMER_IrqHandler, &g_timer1); + + HAL_TIMER_RegisterCallback(&g_timer1, TIMER_PERIOD_FIN, MotorStatemachineCallBack); + IRQ_SetPriority(IRQ_TIMER1, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_TIMER1); +} + +__weak void UART0InterruptErrorCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_TRNS_IT_ERROR */ + /* USER CODE END UART0_TRNS_IT_ERROR */ +} + +__weak void UART0_TXDMACallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_WRITE_DMA_FINISH */ + /* USER CODE END UART0_WRITE_DMA_FINISH */ +} + +__weak void UART0WriteInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_WRITE_IT_FINISH */ + /* USER CODE END UART0_WRITE_IT_FINISH */ +} + +__weak void UART0ReadInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_READ_IT_FINISH */ + /* USER CODE END UART0_READ_IT_FINISH */ +} + +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAND_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_DMA; + g_uart0.rxMode = UART_MODE_INTERRUPT; + g_uart0.fifoMode = BASE_CFG_ENABLE; + g_uart0.fifoTxThr = UART_FIFODEPTH_SIZE8; + g_uart0.fifoRxThr = UART_FIFODEPTH_SIZE8; + g_uart0.hwFlowCtr = BASE_CFG_DISABLE; + g_uart0.handleEx.overSampleMultiple = UART_OVERSAMPLING_16X; + g_uart0.handleEx.msbFirst = BASE_CFG_DISABLE; + HAL_UART_Init(&g_uart0); + HAL_UART_RegisterCallBack(&g_uart0, UART_TRNS_IT_ERROR, (UART_CallbackType)UART0InterruptErrorCallback); + HAL_UART_RegisterCallBack(&g_uart0, UART_READ_IT_FINISH, (UART_CallbackType)UART0ReadInterruptCallback); + IRQ_Register(IRQ_UART0, HAL_UART_IrqHandler, &g_uart0); + IRQ_SetPriority(IRQ_UART0, 6); /* 6 is priority value */ + IRQ_EnableN(IRQ_UART0); + g_uart0.dmaHandle = &g_dmac; + g_uart0.uartDmaTxChn = 0; + HAL_UART_RegisterCallBack(&g_uart0, UART_WRITE_DMA_FINISH, (UART_CallbackType)UART0_TXDMACallback); + HAL_UART_RegisterCallBack(&g_uart0, UART_WRITE_IT_FINISH, (UART_CallbackType)UART0WriteInterruptCallback); +} + +static void IOConfig(void) +{ + SYSCTRL0->SC_SYS_STAT.BIT.update_mode = 0; + SYSCTRL0->SC_SYS_STAT.BIT.update_mode_clear = 1; + /* Config PIN39 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_3_AS_UART0_TXD); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_3_AS_UART0_TXD, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_3_AS_UART0_TXD, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_3_AS_UART0_TXD, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_3_AS_UART0_TXD, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN40 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_4_AS_UART0_RXD); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_4_AS_UART0_RXD, PULL_UP); /* Pull-up and Pull-down, UART RX recommend PULL_UP */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_4_AS_UART0_RXD, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_4_AS_UART0_RXD, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_4_AS_UART0_RXD, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN1 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_7_AS_ACMP0_OUT); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_7_AS_ACMP0_OUT, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_7_AS_ACMP0_OUT, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_7_AS_ACMP0_OUT, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_7_AS_ACMP0_OUT, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN48 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_6_AS_ACMP_N2); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_6_AS_ACMP_N2, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_6_AS_ACMP_N2, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_6_AS_ACMP_N2, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_6_AS_ACMP_N2, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN47 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_5_AS_ACMP_P2); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_5_AS_ACMP_P2, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_5_AS_ACMP_P2, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_5_AS_ACMP_P2, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_5_AS_ACMP_P2, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN4 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_6_AS_PGA0_N0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_6_AS_PGA0_N0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_6_AS_PGA0_N0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_6_AS_PGA0_N0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_6_AS_PGA0_N0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN5 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_5_AS_PGA0_P0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_5_AS_PGA0_P0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_5_AS_PGA0_P0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_5_AS_PGA0_P0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_5_AS_PGA0_P0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN3 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_7_AS_PGA0_OUT); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_7_AS_PGA0_OUT, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_7_AS_PGA0_OUT, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_7_AS_PGA0_OUT, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_7_AS_PGA0_OUT, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN7 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_7_AS_ADC_AIN9); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_7_AS_ADC_AIN9, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_7_AS_ADC_AIN9, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_7_AS_ADC_AIN9, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_7_AS_ADC_AIN9, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN2 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_1_AS_ADC_AIN5); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_1_AS_ADC_AIN5, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_1_AS_ADC_AIN5, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_1_AS_ADC_AIN5, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_1_AS_ADC_AIN5, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN14 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_7_AS_ADC_AIN15); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_7_AS_ADC_AIN15, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_7_AS_ADC_AIN15, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_7_AS_ADC_AIN15, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_7_AS_ADC_AIN15, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN11 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_5_AS_PGA1_P0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_5_AS_PGA1_P0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_5_AS_PGA1_P0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_5_AS_PGA1_P0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_5_AS_PGA1_P0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN12 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_6_AS_PGA1_N0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_6_AS_PGA1_N0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_6_AS_PGA1_N0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_6_AS_PGA1_N0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_6_AS_PGA1_N0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN13 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_7_AS_PGA1_OUT); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_7_AS_PGA1_OUT, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_7_AS_PGA1_OUT, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_7_AS_PGA1_OUT, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_7_AS_PGA1_OUT, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN35 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_3_AS_GPIO2_3); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_3_AS_GPIO2_3, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_3_AS_GPIO2_3, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_3_AS_GPIO2_3, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_3_AS_GPIO2_3, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN27 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_0_AS_GPIO1_0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_0_AS_GPIO1_0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_0_AS_GPIO1_0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_0_AS_GPIO1_0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_0_AS_GPIO1_0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN41 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_4_AS_GPIO2_4); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_4_AS_GPIO2_4, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_4_AS_GPIO2_4, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_4_AS_GPIO2_4, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_4_AS_GPIO2_4, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN30 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_4_AS_GPIO4_4); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_4_AS_GPIO4_4, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_4_AS_GPIO4_4, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_4_AS_GPIO4_4, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_4_AS_GPIO4_4, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN26 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_3_AS_GPIO4_3); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_3_AS_GPIO4_3, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_3_AS_GPIO4_3, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_3_AS_GPIO4_3, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_3_AS_GPIO4_3, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN31 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_0_AS_GPIO2_0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_0_AS_GPIO2_0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_0_AS_GPIO2_0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_0_AS_GPIO2_0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_0_AS_GPIO2_0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN32 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_1_AS_GPIO2_1); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_1_AS_GPIO2_1, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_1_AS_GPIO2_1, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_1_AS_GPIO2_1, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_1_AS_GPIO2_1, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN33 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_0_AS_GPIO5_0); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_0_AS_GPIO5_0, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_0_AS_GPIO5_0, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_0_AS_GPIO5_0, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_0_AS_GPIO5_0, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN19 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_0_AS_APT0_PWMA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_0_AS_APT0_PWMA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_0_AS_APT0_PWMA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_0_AS_APT0_PWMA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_0_AS_APT0_PWMA, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN23 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_0_AS_APT0_PWMB); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_0_AS_APT0_PWMB, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_0_AS_APT0_PWMB, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_0_AS_APT0_PWMB, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_0_AS_APT0_PWMB, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN20 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_1_AS_APT1_PWMA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_1_AS_APT1_PWMA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_1_AS_APT1_PWMA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_1_AS_APT1_PWMA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_1_AS_APT1_PWMA, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN24 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_1_AS_APT1_PWMB); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_1_AS_APT1_PWMB, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_1_AS_APT1_PWMB, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_1_AS_APT1_PWMB, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_1_AS_APT1_PWMB, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN21 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_2_AS_APT2_PWMA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_2_AS_APT2_PWMA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_2_AS_APT2_PWMA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_2_AS_APT2_PWMA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_2_AS_APT2_PWMA, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN25 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_2_AS_APT2_PWMB); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_2_AS_APT2_PWMB, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_2_AS_APT2_PWMB, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_2_AS_APT2_PWMB, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_2_AS_APT2_PWMB, DRIVER_RATE_2); /* Output signal edge fast/slow */ +} + +static void APT_SyncMasterInit(void) +{ + HAL_APT_MasterSyncInit(&g_apt0, APT_SYNC_OUT_ON_CNTR_ZERO); +} + +static void APT_SyncSlaveInit(void) +{ + APT_SlaveSyncIn aptSlave; + + aptSlave.cntPhase = 0; /* counter phase value */ + aptSlave.syncCntMode = APT_COUNT_MODE_AFTER_SYNC_UP; + aptSlave.syncInSrc = APT_SYNCIN_SRC_APT0_SYNCOUT; /* sync source selection */ + aptSlave.cntrSyncSrc = APT_CNTR_SYNC_SRC_SYNCIN; + HAL_APT_SlaveSyncInit(&g_apt1, &aptSlave); + + aptSlave.cntPhase = 0; /* counter phase value */ + aptSlave.syncCntMode = APT_COUNT_MODE_AFTER_SYNC_UP; + aptSlave.syncInSrc = APT_SYNCIN_SRC_APT0_SYNCOUT; /* sync source selection */ + aptSlave.cntrSyncSrc = APT_CNTR_SYNC_SRC_SYNCIN; + HAL_APT_SlaveSyncInit(&g_apt2, &aptSlave); + +} + +void SystemInit(void) +{ + IOConfig(); + DMA_Init(); + UART0_Init(); + ACMP0_Init(); + APT0_Init(); + APT1_Init(); + APT2_Init(); + ADC0_Init(); + PGA0_Init(); + PGA1_Init(); + TIMER0_Init(); + TIMER1_Init(); + GPIO_Init(); + + APT_SyncMasterInit(); + APT_SyncSlaveInit(); + + /* USER CODE BEGIN system_init */ + /* USER CODE END system_init */ +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_carrier.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..627f41c6d62a40b3b7ae4cc2a4e0a9217cd19ca0 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_carrier.h @@ -0,0 +1,142 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_carrier.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration for carrier interrupt processing function. + */ +#ifndef McuMagicTag_MCS_CARRIER_H +#define McuMagicTag_MCS_CARRIER_H + +#include "mcs_status.h" +#include "mcs_mtr_param.h" +#include "mcs_svpwm.h" +#include "mcs_curr_ctrl.h" +#include "mcs_if_ctrl.h" +#include "mcs_ramp_mgmt.h" +#include "mcs_spd_ctrl.h" +#include "mcs_fosmo.h" +#include "mcs_smo_4th.h" +#include "mcs_pll.h" +#include "mcs_startup.h" +#include "mcs_r1_svpwm.h" +#include "mcs_fw_ctrl.h" +#include "mcs_prot_user.h" + +typedef void (*MCS_ReadCurrUvwCb)(UvwAxis *CurrUvw); +typedef void (*MCS_SetPwmDutyCb)(UvwAxis *dutyUvwLeft, UvwAxis *dutyUvwRight); +typedef void (*MCS_SetADCTriggerTimeCb)(unsigned short cntCmpSOCA, unsigned short cntCmpSOCB); + +/** + * @brief motor control FSM state define. + * @details motor control FSM state type: + * + FSM_IDLE -- IDLE state, system startup default. + * + FSM_OFFSET_CALIB -- Self calibrate, for ADC init. + * + FSM_CAP_CHARGE -- IPM cap charge. + * + FSM_CLEAR -- Clear before every run. + * + FSM_LOCATE -- Rotor position pre-locate. + * + FSM_STARTUP -- Start up. + * + FSM_SWITCH -- Transition state, control from open to closed loop. + * + FSM_RUN -- Normal running state. + * + FSM_WAIT_STOP -- Wait stopping. + * + FSM_STOP -- Normal stop. + * + FSM_FAULT -- Fault state, waiting for user process. + */ +typedef enum { + FSM_IDLE = 0, + FSM_OFFSET_CALIB, + FSM_CAP_CHARGE, + FSM_CLEAR, + FSM_LOCATE, + FSM_STARTUP, + FSM_SWITCH, + FSM_RUN, + FSM_WAIT_STOP, + FSM_STOP, + FSM_FAULT +} FsmState; + +/** + * @brief Sampling mode. + */ +typedef enum { + DUAL_RESISTORS = 0, + SINGLE_RESISTOR = 1 +} SampleMode; + +/** + * @brief Motor control data structure + */ +typedef struct { + unsigned char motorStateFlag; + float spdCmdHz; /**< External input speed command value */ + float axisAngle; /**< Angle of the synchronous coordinate system */ + float spdRefHz; /**< Command value after speed ramp management */ + float currCtrlPeriod; /**< current loop control period */ + float adc0Compensate; /**< ADC0 softwaretrim compensate value */ + float adc1Compensate; /**< ADC1 softwaretrim compensate value */ + float udc; /**< Bus voltage */ + float powerBoardTemp; /**< Power boart surface temperature */ + unsigned short aptMaxcntCmp; /**< Apt Maximum Comparison Count */ + float adcCurrCofe; /**< Adc current sampling cofeature */ + + unsigned short sysTickCnt; /**< System Timer Tick Count */ + unsigned short capChargeTickNum; /**< Bootstrap Capacitor Charge Tick Count */ + volatile unsigned int msTickCnt; /**< Millisecond-level counter, which can be used in 1-ms and 5-ms tasks. */ + unsigned short msTickNum; /**< Number of ticks corresponding to 1 ms */ + char obserType; /**< Set Observer Type */ + char controlMode; /**< Set foc control or sixstep bldc control mode or others */ + char spdAdjustMode; /**< Set speed adjust mode */ + char uartConnectFlag; /**< Uart connect success flag */ + short uartHeartDetCnt; /**< Uart connect heart detect count */ + float uartTimeStamp; /**< Uart data time stamp */ + SysStatusReg statusReg; /**< System status */ + FsmState stateMachine; /**< Motor Control State Machine */ + + SampleMode sampleMode; /**< sample mode */ + MOTOR_Param mtrParam; /**< Motor parameters */ + FOSMO_Handle smo; /**< SMO observer handle */ + SMO4TH_Handle smo4th; /**< SMO 4th observer handle */ + IF_Handle ifCtrl; /**< I/F control handle */ + SVPWM_Handle sv; /**< SVPWM Handle */ + R1SVPWM_Handle r1Sv; /**< Single-resistance phase-shifted SVPWM handld */ + RMG_Handle spdRmg; /**< Ramp management struct for the speed controller input reference */ + SPDCTRL_Handle spdCtrl; /**< Speed loop Control Handle */ + CURRCTRL_Handle currCtrl; /**< Current loop control handle */ + STARTUP_Handle startup; /**< Startup Switch Handle */ + FW_Handle fw; /**< Flux-Weakening Handle */ + + DqAxis idqRef; /**< Command value of the dq axis current */ + UvwAxis currUvw; /**< Three-phase current sampling value */ + AlbeAxis iabFbk; /**< αβ-axis current feedback value */ + DqAxis idqFbk; /**< Current feedback value of the dq axis */ + DqAxis vdqRef; /**< Current loop output dq voltage */ + AlbeAxis vabRef; /**< Current loop output voltage αβ */ + UvwAxis dutyUvw; /**< UVW three-phase duty cycle */ + UvwAxis dutyUvwLeft; /**< Single Resistor UVW Three-Phase Left Duty Cycle */ + UvwAxis dutyUvwRight; /**< Single Resistor UVW Three-Phase Right Duty Cycle*/ + + MCS_ReadCurrUvwCb readCurrUvwCb; /**< Read current callback function */ + MCS_SetPwmDutyCb setPwmDutyCb; /**< Set the duty cycle callback function. */ + MCS_SetADCTriggerTimeCb setADCTriggerTimeCb; /**< Sets the ADC trigger point callback function. */ + + MotorProtStatus_Handle prot; /**< Protection handle. */ +} MTRCTRL_Handle; + +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_chip_config.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_chip_config.h new file mode 100644 index 0000000000000000000000000000000000000000..fbb9682691af7c2e32dc9fb164a97c84859b5cdf --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_chip_config.h @@ -0,0 +1,73 @@ +/** + * @ Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2022-2023. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_chip_config.h + * @author MCU Algorithm Team + * @brief This file provides config macros for ECMCU105H/ECBMCU201MPC app. + */ + +#ifndef McuMagicTag_MCS_CHIPCONFIG_H +#define McuMagicTag_MCS_CHIPCONFIG_H + +#include "feature.h" + +#ifdef CHIP_3061MNPICA + + #define ADCPTT_HANDLE g_adc0 + #define ADCRESIS_HANDLE g_adc0 + #define ADCUDC_HANDLE g_adc0 + #define ADCU_HANDLE g_adc0 + #define ADCW_HANDLE g_adc0 + #define LED1_HANDLE g_gpio2 + #define LED2_HANDLE g_gpio1 + #define LED2_PIN GPIO_PIN_0 + #define LED1_PIN GPIO_PIN_3 + #define ADCPTTSOCNUM ADC_SOC_NUM0 + #define ADCUSOCNUM ADC_SOC_NUM1 + #define ADCRESISSOCNUM ADC_SOC_NUM3 + #define ADCUDCSOCNUM ADC_SOC_NUM4 + #define ADCWSOCNUM ADC_SOC_NUM6 + + #define ADC0COMPENSATE 2037.0f + #define ADC1COMPENSATE 2027.0f + +#endif + +#if defined (CHIP_3065HRPIRZ) || defined (CHIP_3065ARPIRZ) + + #define ADCU_HANDLE g_adc0 + #define ADCW_HANDLE g_adc1 + #define ADCRESIS_HANDLE g_adc2 + #define ADCUDC_HANDLE g_adc2 + #define ADCPTT_HANDLE g_adc2 + #define LED1_HANDLE g_gpio0 + #define LED2_HANDLE g_gpio0 + #define LED2_PIN GPIO_PIN_6 + #define LED1_PIN GPIO_PIN_7 + #define ADCPTTSOCNUM ADC_SOC_NUM0 + #define ADCRESISSOCNUM ADC_SOC_NUM1 + #define ADCUSOCNUM ADC_SOC_NUM8 + #define ADCWSOCNUM ADC_SOC_NUM8 + #define ADCUDCSOCNUM ADC_SOC_NUM14 + + #define ADC0COMPENSATE 2033.0f + #define ADC1COMPENSATE 2070.0f + +#endif + + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_ctlmode_config.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_ctlmode_config.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6f38cccf3fb92d52b4874390805a520e255b2f --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_ctlmode_config.h @@ -0,0 +1,73 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_ctlmode_config.h + * @author MCU Algorithm Team + * @brief This file provides config macros for ECMCU105H app. + */ + + /* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_CTLMODECONFIG_H +#define McuMagicTag_MCS_CTLMODECONFIG_H + +#include "debug.h" +#include "typedefs.h" + +typedef enum { + FOC_STARTUP_IF = 0, + FOC_STARTUP_VF, + FOC_STARTUP_HFI +} MOTOR_STARTUPMODE_CONFIG; + +typedef enum { + FOC_OBSERVERTYPE_SMO1TH = 0, + FOC_OBSERVERTYPE_SMO1TH_PLL, + FOC_OBSERVERTYPE_SMO4TH, + FOC_OBSERVERTYPE_SMO4TH_PLL, + FOC_OBSERVERTYPE_LUNBORG, + FOC_OBSERVERTYPE_FLUX +} MOTOR_OBSERVERTYPE_CONFIG; + +typedef enum { + FOC_CONTROLMODE_SPEED = 0, + FOC_CONTROLMODE_TORQUE +} MOTOR_CONTROLMODE_CONFIG; + +typedef enum { + FOC_CURQAXISPID_PARAMS = 0, + FOC_CURDAXISPID_PARAMS, + FOC_SPDPID_PARAMS +} MOTOR_PID_SET; + +typedef enum { + MOTOR_PARAMS_BASE = 0, + MOTOR_PARAMS_SPECIAL, + MOTOR_PARAMS_BOARD +} MOTOR_PARAMS_SET; + +typedef enum { + CUST_SPEED_ADJUST = 0, + HOST_SPEED_ADJUST +} MODE_ADSPEED_CONFIG; + +typedef enum { + CONNECTING = 0, + CONNECTED, + DISCONNECT +} UART_STATUS; + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_motor_process.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..783bf21402d5d3f5d4bdc8dc5bd9ee425d0fbf21 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_motor_process.h @@ -0,0 +1,45 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_motor_process.h + * @author MCU Algorithm Team + * @brief This file provides motor sample functions declaration for ECMCU105H board. + */ +#ifndef McuMagicTag_MCS_MOTOR_PROCESS_H +#define McuMagicTag_MCS_MOTOR_PROCESS_H + +/** + * @brief phase sequence. + */ +typedef enum { + PHASE_U = 0, + PHASE_V, + PHASE_W, + PHASE_MAX_NUM +} MCS_PhaseEnum; + +/** + * @brief key state. + */ +typedef enum { + KEY_DOWN = 0, + KEY_UP = 1, +} KEY_State; + +int MotorMainProcess(void); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_status.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..19510c78b2d63a46ca51495d8ad028e351574d1d --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_status.h @@ -0,0 +1,188 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_status.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of system status. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_STATUS_H +#define McuMagicTag_MCS_STATUS_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "typedefs.h" +#include "mcs_assert.h" + +/* Typedef definitions ------------------------------------------------------------------------- */ +/** + * @brief System status define + */ +typedef union { + unsigned short all; + struct { + unsigned short cmdStart : 1; /**< Indicates that a start system command has been received. */ + unsigned short cmdStop : 1; /**< Indicates that a stop system command has been received. */ + unsigned short isRunning : 1; /**< Indicates that the system is running (enable signal) */ + unsigned short sysError : 1; /**< Indicates that the system reports an error. */ + unsigned short poweron : 1; /**< Indicates that the power-on initialization phase is complete. */ + unsigned short capcharge : 1; /**< Indicates that the bootstrap capacitor charging phase is complete. */ + unsigned short adczero : 1; /**< The current sampling point is reset to zero after power-on. */ + } Bit; +} SysStatusReg; + +/** + * @brief Get status of Bit cmdStart. + * @param sysStatus System status register handle. + * @retval Status of Bit cmdStart. + */ +static inline bool SysGetCmdStart(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + bool ret; + ret = (sysStatus->Bit.cmdStart == 1) ? true : false; + return ret; +} + +/** + * @brief Set Bit cmdStart. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysCmdStartSet(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.cmdStart = 1; +} + +/** + * @brief Clear Bit cmdStart. + * @param handle System status register handle. + * @retval None. + */ +static inline void SysCmdStartClr(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.cmdStart = 0; +} + +/** + * @brief Get status of Bit cmdStop. + * @param sysStatus System status register handle. + * @retval Status of Bit cmdStart. + */ +static inline bool SysGetCmdStop(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + bool ret; + ret = (sysStatus->Bit.cmdStop == 1) ? true : false; + return ret; +} + +/** + * @brief Set Bit cmdStop. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysCmdStopSet(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.cmdStop = 1; +} + +/** + * @brief Clear Bit cmdStop. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysCmdStopClr(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.cmdStop = 0; +} + +/** + * @brief Get status of Bit isRunning. + * @param sysStatus System status register handle. + * @retval Status of Bit isRunning. + */ +static inline bool SysIsRunning(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + bool ret; + ret = (sysStatus->Bit.isRunning == 1) ? true : false; + return ret; +} + +/** + * @brief Set Bit isRuning. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysRunningSet(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.isRunning = 1; +} + +/** + * @brief Clear Bit isRuning. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysRunningClr(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.isRunning = 0; +} + +/** + * @brief Get status of Bit sysError. + * @param sysStatus System status register handle. + * @retval Status of Bit sysError. + */ +static inline bool SysIsError(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + bool ret; + ret = (sysStatus->Bit.sysError == 1) ? true : false; + return ret; +} + +/** + * @brief Set Bit sysError. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysErrorSet(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.sysError = 1; +} + +/** + * @brief Clear Bit sysError. + * @param sysStatus System status register handle. + * @retval None. + */ +static inline void SysErrorClr(SysStatusReg *sysStatus) +{ + MCS_ASSERT_PARAM(sysStatus != NULL); + sysStatus->Bit.sysError = 0; +} + +#endif diff --git a/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_user_config.h b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..4eff5446d903abd905e17fc0c34cd2f59094d668 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/inc/mcs_user_config.h @@ -0,0 +1,106 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_user_config.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of user config parameters. + */ +#ifndef McuMagicTag_MCS_CONFIG_H +#define McuMagicTag_MCS_CONFIG_H + +#include "debug.h" +#include "typedefs.h" + +#define SMO4TH + +#define SYSTICK_PERIOD_US 500u /* systick period */ + +#define INV_CAP_CHARGE_MS 3u + +#define INV_VOLTAGE_BUS 12.0f /* Bus voltage, V */ + +#define CTRL_CURR_PERIOD 0.0001f /* carrier ISR period, 100us */ +#define CTRL_SYSTICK_PERIOD 0.0005f /* systick control period, 500us */ + +/* Duty of sample window, the real time is 0.06*50us = 3us. */ +#define SAMPLE_WINDOW_DUTY 0.06f + +/* Duty of sample point shift as flip point, the real time is 0.008*50us = 0.4us. */ +#define SAMPLE_POINT_SHIFT 0.008f + +/* Sampling resistance 200mOhm 0.0013295 */ +#define ADC_CURR_COFFI 0.0013295f /* 3.3/4096/3.03/0.2 pga: 3.03, 200mohm */ +/* APT */ +#define APT_SYNC_IN_SRC APT_SYNCIN_SRC_APT0_SYNCOUT + +#define APT_U APT0_BASE /* Base address of U phase APT module */ +#define APT_V APT1_BASE /* Base address of V phase APT module */ +#define APT_W APT2_BASE /* Base address of W phase APT module */ + +/* FOSMO */ +#define FOSMO_GAIN 4.0f /* SMO gain */ +#define FOSMO_LAMBDA 2.0f /* SMO coefficient of cut-off frequency, its value = lambda * we */ +#define FOSMO_EMF_CUTOFF_FREQ 2.0f /* SMO back emf cutoff frequency. */ +#define SPEED_FILTER_CUTOFF_FREQUENCY 40.0f /* SMO speed cutoff frequency. of speed filter. */ +#define FOSMO_PLL_BDW 30.0f /* SMO PLL bandwidth. */ + +/* SMO4TH */ +#define SMO4TH_PLL_BDW 30.0f +#define SMO4TH_KD 300.0f +#define SMO4TH_KQ 600.0f +#define SMO4TH_SPD_FILTER_CUTOFF_FREQ 40.0f + +/* User_Commond */ +#define CTRL_IF_CURR_AMP_A 0.07f /* IF control current amplitude */ +#define USER_TARGET_SPD_HZ 100.0f /* Parentheses are used to enter negative instructions */ +#define USER_SWITCH_SPDBEGIN_HZ 30.0f /* Start of handover interval */ +#define USER_SWITCH_SPDEND_HZ (USER_SWITCH_SPDBEGIN_HZ + 3.0f) /* End of handover period */ +#define USER_MAX_SPD_HZ 180.25f +#define USER_MIN_SPD_HZ 35.0f +#define USER_SPD_SLOPE 50.0f /* slope of velocity change */ +#define USER_CURR_SLOPE (CTRL_IF_CURR_AMP_A * 10.0f) /* Current change slope */ + +/* PID PARAMS */ +#define CURRQAXIS_KP 5.023202f +#define CURRQAXIS_KI 20612.84f +#define CURRDAXIS_KP 3.477114f +#define CURRDAXIS_KI 20612.84f +#define CURR_LOWERLIM (-INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.95f) +#define CURR_UPPERLIM (INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.95f) + +#define SPD_KP 0.00505f +#define SPD_KI 0.012f +#define SPD_LOWERLIM -0.105f +#define SPD_UPPERLIM 0.105f + +/* MOTOR PARAMS */ +/* Np, Rs, Ld, Lq, Psif, J, Nmax, Currmax, PPMR, zShift */ +/* mtrPsif & mtrJ parameter is not used in this project, temporarily set to 0 */ +#define MOTORPARAM_DEFAULTS { \ + .mtrNp = 7, \ + .mtrRs = 5.1f, \ + .mtrLd = 0.00133f, \ + .mtrLq = 0.00133f, \ + .mtrPsif = 0.0f, \ + .mtrJ = 0.0f, \ + .maxElecSpd = 180.25f, \ + .maxCurr = 0.105f, \ +} + +#define ADC_UDC_COFFI 0.01289f /* 0.01289 = 3.3/4096*192/12 */ + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.c new file mode 100644 index 0000000000000000000000000000000000000000..99766bdf9b3d4f161b1902708696cb0e75a4fc9c --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.c @@ -0,0 +1,43 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_prot_cmm.c + * @author MCU Algorithm Team + * @brief This file contains protection common api definition. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "apt.h" +#include "mcs_assert.h" + +/** + * @brief Safty-pulse-off function execution to turn off all the power devices. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void ProtSpo_Exec(APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + /**< Turn off all the six power devices of the inverter. */ + for (unsigned int i = 0; i < MOTOR_PHASE_NUMBER; i++) { + APT_RegStruct *aptx = (APT_RegStruct *)(aptAddr[i]); + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_ForcePWMOutputLow(aptx); + } +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.h new file mode 100644 index 0000000000000000000000000000000000000000..104a5decba9eeb22375b63e4def4278af37d3573 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_cmm.h @@ -0,0 +1,136 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_prot_cmm.h + * @author MCU Algorithm Team + * @brief This file contains protection function common data struct and api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_PROT_CMM_H +#define McuMagicTag_MCS_PROT_CMM_H + +#include "typedefs.h" +#include "apt_ip.h" + +/* Macro definitions --------------------------------------------------------------------------- */ +#define MOTOR_PHASE_NUMBER (3) + +#define PROT_VAL_THRESHOLD_NUMS (4) +#define PROT_VAL_THRESHOLD_0 (0) +#define PROT_VAL_THRESHOLD_1 (1) +#define PROT_VAL_THRESHOLD_2 (2) +#define PROT_VAL_THRESHOLD_3 (3) + +#define PROT_LIMIT_TIME_NUMS (3) +#define PROT_LIMIT_TIME_0 (0) +#define PROT_LIMIT_TIME_1 (1) +#define PROT_LIMIT_TIME_2 (2) + +#define MOTOR_PHASE_NUMBER (3) + +/**< Motor error status definition. */ +typedef union { + int all; + struct { + unsigned short overCurrErr : 1; /**< Indicates that phase current(s) is over protected value. */ + unsigned short overVoltErr : 1; /**< Indicates that dc-link voltage is over protected value. */ + unsigned short lowerVoltErr : 1; /**< Indicates that dc-link voltage is lower than protected value */ + unsigned short overIpmTempErr : 1; /**< Indicates that IPM temperature is over protected value. */ + unsigned short revRotErr : 1; /**< Indicates that motor negtive direction. */ + unsigned short motorStalling : 1; /**< Indicates that rotor is stalling. */ + unsigned short overMotorTempErr : 1; /**< Indicates that three phase currents is out-of-balance. */ + unsigned short posSnsrCommsErr : 1; /**< Indicates that position sensor communication is lost with MCU. */ + unsigned short posSnsrFuncErr : 1; /**< Indicates that position sensor reports function error. */ + unsigned short posSnsrCalibrErr : 1; /**< Indicates that position sensor fails to calibrate itself. */ + unsigned short currOutOfBalance : 1; /**< Indicates that the rotor is reverse rotation.*/ + unsigned short phsOpenErr : 1; /**< Indicates that phase winding(s) is open. */ + unsigned short phsU : 1; /**< Indicates that u phase fails when phsOpenErr occurs. */ + unsigned short phsV : 1; /**< Indicates that v phase fails when phsOpenErr occurs. */ + unsigned short phsW : 1; /**< Indicates that w phase fails when phsOpenErr occurs. */ + unsigned short multiPhs : 1; /**< Indicates that multi-phases fail when phsOpenErr occurs.*/ + } Bit; +} MotorErrStatusReg; + +/**< Protection Status Bit Definition */ +typedef enum { + OCP_ERR_BIT, + OVP_ERR_BIT, + LVP_ERR_BIT, + OTP_IPM_ERR_BIT, + OTP_MOTOR_ERR_BIT, + STALLING_ERR_BIT, + CURR_OUT_BALANCE_ERR_BIT, + POS_COMMS_ERR_BIT, + POS_FUNC_ERR_BIT, + POS_CALIB_ERR_BIT, + REV_ROT_ERR_BIT, + PHS_OPEN_ERR_BIT, + PHS_U_ERR_BIT, + PHS_V_ERR_BIT, + PHS_W_ERR_BIT, + PHS_MULTI_ERR_BIT, +} PROT_ErrBit; + +/**< Motor error protection level. */ +typedef enum { + PROT_LEVEL_0 = 0, + PROT_LEVEL_1, + PROT_LEVEL_2, + PROT_LEVEL_3, + PROT_LEVEL_4 /**< The greater level number, the severe error is. */ +} PROT_Level; + +/** + * @brief Obtains the status of a bit of data. + * @param data data. + * @param bits Number of digits. + * @retval Bit status. + */ +static inline bool GetBit(int data, unsigned short bit) +{ + bool ret; + ret = ((data >> bit) & 1); + return ret; +} + +/** + * @brief Sets the status of a bit of data. + * @param data data. + * @param bit The setted bit. + * @retval None. + */ +static inline void SetBit(int *data, unsigned char bit) +{ + *data |= (1 << bit); +} + +/** + * @brief Clear the status of a bit of data. + * @param data data. + * @param bit The Clear bit. + * @retval None. + */ +static inline void ClearBit(int *data, unsigned char bit) +{ + *data &= ~(1 << bit); +} + +/**< Protection action. */ +void ProtSpo_Exec(APT_RegStruct **aptAddr); + +#endif diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.c new file mode 100644 index 0000000000000000000000000000000000000000..e97876b7c6ec522fa82c30cbe503e2ab8de288db --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.c @@ -0,0 +1,137 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_prot_user.c + * @author MCU Algorithm Team + * @brief This file contains user protection data struct, inquiry api and initialization api definition. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_user.h" +#include "mcs_prot_user_config.h" +#include "mcs_assert.h" + +/** + * @brief Get motor over current error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsMotorOverCurrErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.overCurrErr) { + return true; + } else { + return false; + } +} + +/** + * @brief Get motor over dc-link voltage error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsDcLinkOverVoltErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.overVoltErr) { + return true; + } else { + return false; + } +} + +/** + * @brief Get motor lower dc-link voltage error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsDcLinkLowerVoltErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.lowerVoltErr) { + return true; + } else { + return false; + } +} + +/** + * @brief Get motor over Ipm temperature error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsIpmOverTempErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.overIpmTempErr) { + return true; + } else { + return false; + } +} + +/** + * @brief Get motor over Motor temperature error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsMotorOverTempErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.overMotorTempErr) { + return true; + } else { + return false; + } +} + +/** + * @brief Get motor stalling error status. + * @param motorErrStatus Motor error status. + * @retval Error status. + */ +bool IsMotorStallingErr(MotorErrStatusReg motorErrStatus) +{ + if (motorErrStatus.Bit.motorStalling) { + return true; + } else { + return false; + } +} + +/** + * @brief Clear the motor error status. + * @param motorProt Motor protection handle. + * @retval Error status. + */ +void ClearMotorErrStatus(MotorProtStatus_Handle *motorProt) +{ + MCS_ASSERT_PARAM(motorProt != NULL); + /* Clear the motor error status. */ + motorProt->motorErrStatus.all = 0x00; + OCP_Clear(&motorProt->ocp); + OVP_Clear(&motorProt->ovp); + LVP_Clear(&motorProt->lvp); + OTP_Clear(&motorProt->otp); +} + +/** + * @brief Motor protection function initialization. + * @param motorProt Motor protection handle. + * @retval Error status. + */ +void MotorProt_Init(MotorProtStatus_Handle *motorProt) +{ + MCS_ASSERT_PARAM(motorProt != NULL); + motorProt->motorErrStatus.all = 0x00; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.h new file mode 100644 index 0000000000000000000000000000000000000000..365110e10c6cd8bd5207af61f0a87b6df226fa91 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user.h @@ -0,0 +1,54 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_prot_user.h + * @author MCU Algorithm Team + * @brief This file contains user protection data struct, inquiry api and initialization api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_PROT_USER_H +#define McuMagicTag_MCS_PROT_USER_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "mcs_curr_prot.h" +#include "mcs_dc_volt_prot.h" +#include "mcs_temp_prot.h" +#include "mcs_motor_stalling.h" +#include "typedefs.h" + +typedef struct { + MotorErrStatusReg motorErrStatus; /**< Motor error status. */ + OCP_Handle ocp; /**< Over current protection. */ + OVP_Handle ovp; /**< Over dc-link voltage protection. */ + LVP_Handle lvp; /**< Lower dc-link voltage protection. */ + OTP_Handle otp; /**< Over IPM temperature protection. */ + STP_Handle stall; /**< Motor stalling protection. */ +} MotorProtStatus_Handle; + +void MotorProt_Init(MotorProtStatus_Handle *motorProt); + +/**< Inquiry motor error status */ +bool IsMotorOverCurrErr(MotorErrStatusReg motorErrStatus); +bool IsDcLinkOverVoltErr(MotorErrStatusReg motorErrStatus); +bool IsDcLinkLowerVoltErr(MotorErrStatusReg motorErrStatus); +bool IsIpmOverTempErr(MotorErrStatusReg motorErrStatus); +bool IsMotorOverTempErr(MotorErrStatusReg motorErrStatus); +bool IsMotorStallingErr(MotorErrStatusReg motorErrStatus); +void ClearMotorErrStatus(MotorProtStatus_Handle *motorProt); +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user_config.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..3f43e7736e6f4d6a7e7377b5c2689be1755690da --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/common/mcs_prot_user_config.h @@ -0,0 +1,125 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_prot_user_config.h + * @author MCU Algorithm Team + * @brief This file contans user macro definition of the protection function. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_PROT_USER_CONFIG_H +#define McuMagicTag_MCS_PROT_USER_CONFIG_H + +/* Macro definitions --------------------------------------------------------------------------- */ +/**< COMMON */ +/**< Peak phase current (A) of the motor or IPM under continuous operations. */ +#define PROT_MOTOR_RATED_CURR (0.07f) +/**< Only several continuous fault detection can trigger error status. */ +#define PROT_CNT_LIMIT (100) +/**< Only several contunuous none fault dectection can trigger elimination of error status. */ +#define RECY_CNT_LIMIT (10000) +/**< Only several contunuous none fault dectection can trigger elimination of error status. */ +#define OVER_VOLT_RECY_CNT_LIMIT (100) +/**< Only several contunuous none fault dectection can trigger elimination of error status. */ +#define LOWER_VOLT_RECY_CNT_LIMIT (100) + +/**< Over current protection */ +/**< Over current trigger value (A) when in level 1. */ +#define PROT_OVER_CURR_POW_DN1 (2.0f * PROT_MOTOR_RATED_CURR) +/**< Over current trigger value (A) when in level 2. */ +#define PROT_OVER_CURR_POW_DN2 (2.0f * PROT_MOTOR_RATED_CURR) +/**< Over current trigger value (A) when in level 3. */ +#define PROT_OVER_CURR_POW_DN3 (2.0f * PROT_MOTOR_RATED_CURR) +/**< Over current trigger value (A) when in level 4. */ +#define PROT_OVER_CURR_POW_OFF (2.0f * PROT_MOTOR_RATED_CURR) +#define PROT_OVER_CURR_RECY_DELTA (0.0035f) /**< Current gap (A) when recovers from protection status. */ +#define PROT_OVER_CURR_LIMIT1_TIME_SEC (30.0f) /**< 20% overload can last maximum time: 30 sec. */ +#define PROT_OVER_CURR_LIMIT2_TIME_SEC (10.0f) /**< 20% overload can last maximum time: 10 sec. */ +#define PROT_OVER_CURR_LIMIT3_TIME_SEC (2.0f) /**< 20% overload can last maximum time: 2 sec. */ + +/**< Over voltage protection */ +#define PROT_OVER_VOLT_BRK_ON1 (15.0f) /**< Over dc-link voltage trigger value (V) when in level 1. */ +#define PROT_OVER_VOLT_BRK_ON2 (16.0f) /**< Over dc-link voltage trigger value (V) when in level 2. */ +#define PROT_OVER_VOLT_BRK_ON3 (17.0f) /**< Over dc-link voltage trigger value (V) when in level 3. */ +#define PROT_OVER_VOLT_BRK_ALL (18.0f) /**< Over dc-link voltage trigger value (V) when in level 4. */ +#define PROT_OVER_VOLT_RECY_DELTA (0.5f) /**< Voltage gap (V) when recovers from protection status. */ +#define PROT_OVER_VOLT_LIMIT1_TIME_SEC (5.0f) /**< overload1 can last maximum time (sec). */ +#define PROT_OVER_VOLT_LIMIT2_TIME_SEC (3.0f) /**< overload2 can last maximum time (sec). */ +#define PROT_OVER_VOLT_LIMIT3_TIME_SEC (1.0f) /**< overload3 can last maximum time (sec). */ +#define PROT_POW_DN1_PCT (1.0f) /* Power down level in level 1. */ +#define PROT_POW_DN2_PCT (1.0f) /* Power down level in level 2. */ +#define PROT_POW_DN3_PCT (1.0f) /* Power down level in level 3. */ + +/**< Conduction duty needs to be calibrated with the power of the brake loop. */ +#define PROT_OVER_VOLT_BRK_DUTY1 (0.25f) /**< Conduction duty of the brake loop in level 1. */ +#define PROT_OVER_VOLT_BRK_DUTY2 (0.50f) /**< Conduction duty of the brake loop in level 2. */ +#define PROT_OVER_VOLT_BRK_DUTY3 (0.75f) /**< Conduction duty of the brake loop in level 3. */ +#define PROT_OVER_VOLT_BRK_DUTY4 (1.00f) /**< Conduction duty of the brake loop in level 4. */ + +/**< Lower voltage protection */ +#define PROT_LOWER_VOLT_POW_DN1 (10.3f) /**< Lower dc-link voltage trigger value (V) when in level 1. */ +#define PROT_LOWER_VOLT_POW_DN2 (10.0f) /**< Lower dc-link voltage trigger value (V) when in level 2. */ +#define PROT_LOWER_VOLT_POW_DN3 (9.0f) /**< Lower dc-link voltage trigger value (V) when in level 3. */ +#define PROT_LOWER_VOLT_POW_OFF (8.0f) /**< Lower dc-link voltage trigger value (V) when in level 4. */ +#define PROT_LOWER_VOLT_RECY_DELTA (0.5f) /**< Voltage gap (A) when recovers from protection status. */ +#define PROT_LOWER_VOLT_LIMIT1_TIME_SEC (3.0f) /**< 20% overload can last maximum time: 3 sec. */ +#define PROT_LOWER_VOLT_LIMIT2_TIME_SEC (3.0f) /**< 20% overload can last maximum time: 3 sec. */ +#define PROT_LOWER_VOLT_LIMIT3_TIME_SEC (3.0f) /**< 20% overload can last maximum time: 3 sec. */ + +/**< Over IPM temperature protection */ +#define PROT_OVER_IPM_TEMP_POW_DN1 (40.0f) /**< Over IPM temperature trigger value (celsius) when in level 1. */ +#define PROT_OVER_IPM_TEMP_POW_DN2 (42.0f) /**< Over IPM temperature trigger value (celsius) when in level 2. */ +#define PROT_OVER_IPM_TEMP_POW_DN3 (44.0f) /**< Over IPM temperature trigger value (celsius) when in level 3. */ +#define PROT_OVER_IPM_TEMP_POW_OFF (45.0f) /**< Over IPM temperature trigger value (celsius) when in level 4. */ +#define PROT_OVER_IPM_TEMP_RECY_DELTA (0.5f) /**< Temperature gap (celsius) when recovers from protection status. */ +#define PROT_OVER_TEMP_LIMIT1_TIME_SEC (10.0f) /**< 20% overload can last maximum time: 10 sec. */ +#define PROT_OVER_TEMP_LIMIT2_TIME_SEC (10.0f) /**< 20% overload can last maximum time: 10 sec. */ +#define PROT_OVER_TEMP_LIMIT3_TIME_SEC (10.0f) /**< 20% overload can last maximum time: 10 sec. */ + +/**< Motor stalling detection */ +/**< Feedback current higher than this value triggers fault. (A). */ +#define PROT_STALLING_CURR_AMP_LIMIT (PROT_MOTOR_RATED_CURR * 1.2f) +/**< Feedback speed lower than this value triggers fault (Hz). */ +#define PROT_STALLING_SPD_LIMIT 30 +/**< The threshold time that current and speed feedback over ranges (s). */ +#define PROT_STALLING_TIME_LIMIT (1.5f) + +/**< Current out-of-balance detection */ +#define UNBAL_STARTUP_DETECT_TIME_SEC (0.5f) /**< Start detection delay (s) */ +#define UNBAL_PROT_CNT_LIMIT (50000) +#define UNBAL_RECY_CNT_LIMIT (50000) +#define UNBAL_CURRENT_DELTA (1.5f) /**< Used to detect zero crossings in the current cycle. */ +#define UNBAL_DEGREE_LIMIT (0.035f) /**< unbalance degree threshold. */ +#define UNBAL_DEGREE_AVG_FLT_COFFI (0.03f) /**< unbalance degree average Filter coefficient. */ + +/**< Position sensor detection */ +#define POS_SNSR_FAULT_CNT (100000) /* Number of consecutive fault times */ +#define POS_SNSR_RECY_CNT (10000) /* Number of consecutive communication loss times */ + +/**< Phase winding integrity detection */ +#define OPEN_PHS_CURR_THR_A (0.1f) /* Threshold to determine open phase no current (A). */ + +/**< Position sensor zero position detection */ +#define POS_SNSR_CALIBR_UD_REF (15.0f) /* V */ +#define POS_SNSR_CALIBR_UD_SLOPE (15.0f) /* (V/S) */ +#define POS_SNSR_CALIBR_DETECT_TIME (2.0f) /* S */ +#define POS_SNSR_RECORD_TIMES (2000) /* 2000 * TS */ + +/* Multi-cycle mode: > 1; One-cycle mode: < 0.5 */ +#define POS_SNSR_IPD_INJ_PERIOD (4) + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..da4e56f89a51d39053fad4511bb799c91070df65 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.c @@ -0,0 +1,267 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_curr_prot.c + * @author MCU Algorithm Team + * @brief This file contains current protecion api definition. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_curr_prot.h" +#include "mcs_math.h" +#include "mcs_prot_user_config.h" +#include "mcs_assert.h" + +/** + * @brief Initilization over current protection function. + * @param ocp Over current protection handle. + * @param ts Ctrl period (s). + * @retval None. + */ +void OCP_Init(OCP_Handle *ocp, float ts) +{ + MCS_ASSERT_PARAM(ocp != NULL); + MCS_ASSERT_PARAM(ts > 0.0f); + ocp->ts = ts; + OCP_Clear(ocp); + + ocp->protCntLimit = PROT_CNT_LIMIT; + ocp->recyCntLimit = RECY_CNT_LIMIT; + /* Configuring four levels of current protection thresholds. */ + ocp->protValThr[PROT_VAL_THRESHOLD_0] = PROT_OVER_CURR_POW_DN1; + ocp->protValThr[PROT_VAL_THRESHOLD_1] = PROT_OVER_CURR_POW_DN2; + ocp->protValThr[PROT_VAL_THRESHOLD_2] = PROT_OVER_CURR_POW_DN3; + ocp->protValThr[PROT_VAL_THRESHOLD_3] = PROT_OVER_CURR_POW_OFF; + /* Configure the protection limit time. */ + ocp->protLimitTime[PROT_LIMIT_TIME_0] = PROT_OVER_CURR_LIMIT1_TIME_SEC; + ocp->protLimitTime[PROT_LIMIT_TIME_1] = PROT_OVER_CURR_LIMIT2_TIME_SEC; + ocp->protLimitTime[PROT_LIMIT_TIME_2] = PROT_OVER_CURR_LIMIT3_TIME_SEC; + ocp->recyDelta = PROT_OVER_CURR_RECY_DELTA; +} + +/** + * @brief Over current protection detection. + * @param ocp Over current protection handle. + * @param motorErrStatus Motor error status. + * @param idq DQ-axis feedback currents. + * @retval None. + */ +void OCP_Det(OCP_Handle *ocp, MotorErrStatusReg *motorErrStatus, DqAxis idq) +{ + MCS_ASSERT_PARAM(ocp != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + /* Calculate current amplitude. */ + ocp->currAmp = Sqrt(idq.d * idq.d + idq.q * idq.q); + + /* Check if value goes over threshold for continuous cycles. */ + if (ocp->currAmp < ocp->protValThr[PROT_VAL_THRESHOLD_0]) { + ocp->protCnt = 0; + return; + } + + if (ocp->protCnt < ocp->protCntLimit) { + ocp->protCnt++; + return; + } + + /* Check which protection level should be activated. */ + /* Once enter error status, error status can only be changed by recover api. */ + /* protect level: level 4. */ + if (ocp->currAmp >= ocp->protValThr[PROT_VAL_THRESHOLD_3] && ocp->protLevel < PROT_LEVEL_4) { + ocp->protLevel = PROT_LEVEL_4; + motorErrStatus->Bit.overCurrErr = 1; + ocp->protCnt = 0; + return; + } + + /* Protect level: level 3. */ + if (ocp->currAmp >= ocp->protValThr[PROT_VAL_THRESHOLD_2] && ocp->protLevel < PROT_LEVEL_3) { + ocp->protLevel = PROT_LEVEL_3; + motorErrStatus->Bit.overCurrErr = 1; + ocp->protCnt = 0; + ocp->timer = 0.0f; + return; + } + + /* Protect level: level 2. */ + if (ocp->currAmp >= ocp->protValThr[PROT_VAL_THRESHOLD_1] && ocp->protLevel < PROT_LEVEL_2) { + ocp->protLevel = PROT_LEVEL_2; + motorErrStatus->Bit.overCurrErr = 1; + ocp->protCnt = 0; + ocp->timer = 0.0f; + return; + } + + /* Protect level: level 1. */ + if (ocp->currAmp >= ocp->protValThr[PROT_VAL_THRESHOLD_0] && ocp->protLevel < PROT_LEVEL_1) { + ocp->protLevel = PROT_LEVEL_1; + motorErrStatus->Bit.overCurrErr = 1; + ocp->protCnt = 0; + ocp->timer = 0.0f; + return; + } +} + +/** + * @brief Over current protection execution. + * @param ocp Over current protection handle. + * @param idqRef DQ-axis current references. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void OCP_Exec(OCP_Handle *ocp, DqAxis *idqRef, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(ocp != NULL); + MCS_ASSERT_PARAM(idqRef != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + + float id = idqRef->d; + float iq = idqRef->q; + float idqAmp = ocp->currAmp; + /* According to protect level, take corresponding action. */ + switch (ocp->protLevel) { + /* level 4: disable all PWM output. */ + case PROT_LEVEL_4: + /* Disable three-phase pwm output. */ + ProtSpo_Exec(aptAddr); + idqRef->d = 0.0f; + idqRef->q = 0.0f; + break; + + /* level 3: derate speed reference. */ + case PROT_LEVEL_3: + ocp->timer += ocp->ts; + if (ocp->timer > ocp->protLimitTime[PROT_LIMIT_TIME_2]) { + idqRef->d = id / idqAmp * PROT_MOTOR_RATED_CURR; + idqRef->q = iq / idqAmp * PROT_MOTOR_RATED_CURR; + } + break; + + /* level 2: derate speed reference. */ + case PROT_LEVEL_2: + ocp->timer += ocp->ts; + if (ocp->timer > ocp->protLimitTime[PROT_LIMIT_TIME_1]) { + idqRef->d = id / idqAmp * PROT_MOTOR_RATED_CURR; + idqRef->q = iq / idqAmp * PROT_MOTOR_RATED_CURR; + } + break; + + /* level 1: derate speed reference. */ + case PROT_LEVEL_1: + ocp->timer += ocp->ts; + if (ocp->timer > ocp->protLimitTime[PROT_LIMIT_TIME_0]) { + idqRef->d = id / idqAmp * PROT_MOTOR_RATED_CURR; + idqRef->q = iq / idqAmp * PROT_MOTOR_RATED_CURR; + } + break; + + /* level 0: take no protection action. */ + case PROT_LEVEL_0: + break; + + default: + break; + } +} + +/** + * @brief Over current protection recovery. + * @param ocp Over current protection handle. + * @param motorErrStatus Motor error status. + * @retval None. + */ +void OCP_Recy(OCP_Handle *ocp, MotorErrStatusReg *motorErrStatus) +{ + MCS_ASSERT_PARAM(ocp != NULL); + /* If not under error state, just return without any operation. */ + if (!motorErrStatus->Bit.overCurrErr) { + return; + } + + /* Calculate current amplitude. */ + float currAmp = ocp->currAmp; + + /* According to protection level, take corresponding recovery action. */ + switch (ocp->protLevel) { + /* level 4 */ + case PROT_LEVEL_4: + if (currAmp < ocp->protValThr[PROT_VAL_THRESHOLD_3] - ocp->recyDelta) { + ocp->recyCnt++; + if (ocp->recyCnt > ocp->recyCntLimit) { + ocp->protLevel = PROT_LEVEL_3; + ocp->recyCnt = 0; + } + } + break; + + /* level 3 */ + case PROT_LEVEL_3: + if (currAmp < ocp->protValThr[PROT_VAL_THRESHOLD_2] - ocp->recyDelta) { + ocp->recyCnt++; + if (ocp->recyCnt > ocp->recyCntLimit) { + ocp->protLevel = PROT_LEVEL_2; + ocp->recyCnt = 0; + } + } + break; + + /* level 2 */ + case PROT_LEVEL_2: + if (currAmp < ocp->protValThr[PROT_VAL_THRESHOLD_1] - ocp->recyDelta) { + ocp->recyCnt++; + if (ocp->recyCnt > ocp->recyCntLimit) { + ocp->protLevel = PROT_LEVEL_1; + ocp->recyCnt = 0; + } + } + break; + + /* level 1 */ + case PROT_LEVEL_1: + if (currAmp < ocp->protValThr[PROT_VAL_THRESHOLD_0] - ocp->recyDelta) { + ocp->recyCnt++; + if (ocp->recyCnt > ocp->recyCntLimit) { + ocp->protLevel = PROT_LEVEL_0; + ocp->recyCnt = 0; + } + } + break; + + /* level 0 */ + case PROT_LEVEL_0: + motorErrStatus->Bit.overCurrErr = 0; + break; + + default: + break; + } +} + +/** + * @brief Over current protection error status clear. + * @param ocp Over current protection handle. + * @retval None. + */ +void OCP_Clear(OCP_Handle *ocp) +{ + MCS_ASSERT_PARAM(ocp != NULL); + /* Clear the history value. */ + ocp->protCnt = 0; + ocp->protLevel = PROT_LEVEL_0; + ocp->recyCnt = 0; + ocp->timer = 0.0f; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..e9916fe491699bff3373bbc68b175b6db16d7cd7 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_curr_prot.h @@ -0,0 +1,52 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_curr_prot.h + * @author MCU Algorithm Team + * @brief This file contains current protection data struct and api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_MCS_CURR_PROT_H +#define McuMagicTag_MCS_CURR_PROT_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "mcs_typedef.h" +#include "apt_ip.h" + +typedef struct { + unsigned int protCnt; + unsigned int recyCnt; + unsigned int protCntLimit; + unsigned int recyCntLimit; + float currAmp; + float protValThr[PROT_VAL_THRESHOLD_NUMS]; /* from low current level to high. */ + float protLimitTime[PROT_LIMIT_TIME_NUMS]; /* from level 3 to level 1. */ + float recyDelta; + float timer; + float ts; + PROT_Level protLevel; +} OCP_Handle; + +void OCP_Init(OCP_Handle *ocp, float ts); +void OCP_Det(OCP_Handle *ocp, MotorErrStatusReg *motorErrStatus, DqAxis idq); +void OCP_Exec(OCP_Handle *ocp, DqAxis *idqRef, APT_RegStruct **aptAddr); +void OCP_Recy(OCP_Handle *ocp, MotorErrStatusReg *motorErrStatus); +void OCP_Clear(OCP_Handle *ocp); + +#endif diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..b0541a2e2e37ba98e8b92e6334ab2cc940b72b6c --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.c @@ -0,0 +1,495 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_dc_volt_prot.c + * @author MCU Algorithm Team + * @brief This file contains dc-link voltage protection api declaration. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_dc_volt_prot.h" +#include "mcs_prot_user_config.h" +#include "mcs_assert.h" + +/** + * @brief Initilization over dc-link voltage protection function. + * @param ovp Over dc-link voltage protection handle. + * @param ts Ctrl period (s). + * @retval None. + */ +void OVP_Init(OVP_Handle *ovp, float ts) +{ + MCS_ASSERT_PARAM(ovp != NULL); + MCS_ASSERT_PARAM(ts > 0.0f); + ovp->ts = ts; + OVP_Clear(ovp); + ovp->protCntLimit = PROT_CNT_LIMIT; + ovp->recyCntLimit = OVER_VOLT_RECY_CNT_LIMIT; + /* Configuring four levels of overvoltage protection thresholds. */ + ovp->protValThr[PROT_VAL_THRESHOLD_0] = PROT_OVER_VOLT_BRK_ON1; + ovp->protValThr[PROT_VAL_THRESHOLD_1] = PROT_OVER_VOLT_BRK_ON2; + ovp->protValThr[PROT_VAL_THRESHOLD_2] = PROT_OVER_VOLT_BRK_ON3; + ovp->protValThr[PROT_VAL_THRESHOLD_3] = PROT_OVER_VOLT_BRK_ALL; + /* Configure the protection limit time. */ + ovp->protLimitTime[PROT_LIMIT_TIME_0] = PROT_OVER_VOLT_LIMIT1_TIME_SEC; + ovp->protLimitTime[PROT_LIMIT_TIME_1] = PROT_OVER_VOLT_LIMIT2_TIME_SEC; + ovp->protLimitTime[PROT_LIMIT_TIME_2] = PROT_OVER_VOLT_LIMIT3_TIME_SEC; + ovp->recyDelta = PROT_OVER_VOLT_RECY_DELTA; +} + +/** + * @brief Initilization lower dc-link voltage protection function. + * @param lvp Lower dc-link voltage protection handle. + * @param ts Ctrl period (s). + * @retval None. + */ +void LVP_Init(LVP_Handle *lvp, float ts) +{ + MCS_ASSERT_PARAM(lvp != NULL); + MCS_ASSERT_PARAM(ts > 0.0f); + + lvp->ts = ts; + LVP_Clear(lvp); + + lvp->protCntLimit = PROT_CNT_LIMIT; + lvp->recyCntLimit = LOWER_VOLT_RECY_CNT_LIMIT; + /* Configuring four levels of lower voltage protection thresholds. */ + lvp->protValThr[PROT_VAL_THRESHOLD_0] = PROT_LOWER_VOLT_POW_DN1; + lvp->protValThr[PROT_VAL_THRESHOLD_1] = PROT_LOWER_VOLT_POW_DN2; + lvp->protValThr[PROT_VAL_THRESHOLD_2] = PROT_LOWER_VOLT_POW_DN3; + lvp->protValThr[PROT_VAL_THRESHOLD_3] = PROT_LOWER_VOLT_POW_OFF; + /* Configure the protection limit time. */ + lvp->protLimitTime[PROT_LIMIT_TIME_0] = PROT_LOWER_VOLT_LIMIT1_TIME_SEC; + lvp->protLimitTime[PROT_LIMIT_TIME_1] = PROT_LOWER_VOLT_LIMIT2_TIME_SEC; + lvp->protLimitTime[PROT_LIMIT_TIME_2] = PROT_LOWER_VOLT_LIMIT3_TIME_SEC; + lvp->recyDelta = PROT_OVER_VOLT_RECY_DELTA; +} + +/** + * @brief Over dc-link voltage protection detection. + * @param ovp Over dc-link voltage protection handle. + * @param motorErrStatus Motor error status. + * @param udc DC-link voltage feedback (V). + * @retval None. + */ +void OVP_Det(OVP_Handle *ovp, MotorErrStatusReg *motorErrStatus, float udc) +{ + MCS_ASSERT_PARAM(ovp != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(udc > 0.0f); + /* Check if value goes over threshold for continuous cycles. */ + if (udc < ovp->protValThr[PROT_VAL_THRESHOLD_0]) { + ovp->protCnt = 0; + return; + } + + if (ovp->protCnt < ovp->protCntLimit) { + ovp->protCnt++; + return; + } + + /* Check which protection level should be activated. */ + /* Once enter error status, error status can only be changed by recover api. */ + /* protect level: level 4. */ + if (udc >= ovp->protValThr[PROT_VAL_THRESHOLD_3] && ovp->protLevel < PROT_LEVEL_4) { + ovp->protLevel = PROT_LEVEL_4; + motorErrStatus->Bit.overVoltErr = 1; + ovp->protCnt = 0; + return; + } + + /* Protect level: level 3. */ + if (udc >= ovp->protValThr[PROT_VAL_THRESHOLD_2] && ovp->protLevel < PROT_LEVEL_3) { + ovp->protLevel = PROT_LEVEL_3; + motorErrStatus->Bit.overVoltErr = 1; + ovp->protCnt = 0; + ovp->timer = 0.0f; + return; + } + + /* Protect level: level 2. */ + if (udc >= ovp->protValThr[PROT_VAL_THRESHOLD_1] && ovp->protLevel < PROT_LEVEL_2) { + ovp->protLevel = PROT_LEVEL_2; + motorErrStatus->Bit.overVoltErr = 1; + ovp->protCnt = 0; + ovp->timer = 0.0f; + return; + } + + /* Protect level: level 1. */ + if (udc >= ovp->protValThr[PROT_VAL_THRESHOLD_0] && ovp->protLevel < PROT_LEVEL_1) { + ovp->protLevel = PROT_LEVEL_1; + motorErrStatus->Bit.overVoltErr = 1; + ovp->protCnt = 0; + ovp->timer = 0.0f; + return; + } +} + +/** + * @brief Lower dc-link voltage protection detection. + * @param lvp Lower dc-link voltage protection handle. + * @param motorErrStatus Motor error status. + * @param udc DC-link voltage feedback (V). + * @retval None. + */ +void LVP_Det(LVP_Handle *lvp, MotorErrStatusReg *motorErrStatus, float udc) +{ + MCS_ASSERT_PARAM(lvp != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(udc > 0.0f); + /* Check if value goes over threshold for continuous cycles. */ + if (udc > lvp->protValThr[PROT_VAL_THRESHOLD_0]) { + lvp->protCnt = 0; + return; + } + + if (lvp->protCnt < lvp->protCntLimit) { + lvp->protCnt++; + return; + } + + /* Check which protection level should be activated. */ + /* Once enter error status, error status can only be changed by recover api. */ + /* protect level: level 4. */ + if (udc <= lvp->protValThr[PROT_VAL_THRESHOLD_3] && lvp->protLevel < PROT_LEVEL_4) { + lvp->protLevel = PROT_LEVEL_4; + motorErrStatus->Bit.lowerVoltErr = 1; + lvp->protCnt = 0; + return; + } + + /* Protect level: level 3. */ + if (udc <= lvp->protValThr[PROT_VAL_THRESHOLD_2] && lvp->protLevel < PROT_LEVEL_3) { + lvp->protLevel = PROT_LEVEL_3; + motorErrStatus->Bit.lowerVoltErr = 1; + lvp->protCnt = 0; + lvp->timer = 0.0f; + return; + } + + /* Protect level: level 2. */ + if (udc <= lvp->protValThr[PROT_VAL_THRESHOLD_1] && lvp->protLevel < PROT_LEVEL_2) { + lvp->protLevel = PROT_LEVEL_2; + motorErrStatus->Bit.lowerVoltErr = 1; + lvp->protCnt = 0; + lvp->timer = 0.0f; + return; + } + + /* Protect level: level 1. */ + if (udc <= lvp->protValThr[PROT_VAL_THRESHOLD_0] && lvp->protLevel < PROT_LEVEL_1) { + lvp->protLevel = PROT_LEVEL_1; + motorErrStatus->Bit.lowerVoltErr = 1; + lvp->protCnt = 0; + lvp->timer = 0.0f; + return; + } +} + +/** + * @brief Over dc-link voltage protection execution. + * @param ovp Over dc-link voltage protection handle. + * @param duty Brake loop output duty (0-1). + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void OVP_Exec(OVP_Handle *ovp, float *duty, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(ovp != NULL); + MCS_ASSERT_PARAM(duty != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + /* According to protect level, take corresponding action. */ + switch (ovp->protLevel) { + /* level 4: brake loop duty maximum. */ + case PROT_LEVEL_4: + *duty = PROT_OVER_VOLT_BRK_DUTY4; + /* Disable three-phase pwm output. */ + ProtSpo_Exec(aptAddr); + break; + + /* level 3: brake loop duty level 3. */ + case PROT_LEVEL_3: + *duty = PROT_OVER_VOLT_BRK_DUTY2; + ovp->timer += ovp->ts; + if (ovp->timer > ovp->protLimitTime[PROT_LIMIT_TIME_2]) { + *duty = PROT_OVER_VOLT_BRK_DUTY3; + } + break; + + /* level 2: brake loop duty level 2. */ + case PROT_LEVEL_2: + *duty = PROT_OVER_VOLT_BRK_DUTY1; + ovp->timer += ovp->ts; + if (ovp->timer > ovp->protLimitTime[PROT_LIMIT_TIME_1]) { + *duty = PROT_OVER_VOLT_BRK_DUTY2; + } + break; + + /* level 1: brake loop duty level 1. */ + case PROT_LEVEL_1: + ovp->timer += ovp->ts; + if (ovp->timer > ovp->protLimitTime[PROT_LIMIT_TIME_0]) { + *duty = PROT_OVER_VOLT_BRK_DUTY1; + } + break; + + /* level 0: take no protection action. */ + case PROT_LEVEL_0: + break; + + default: + break; + } + return; +} + +/** + * @brief Lower dc-link voltage protection execution. + * @param lvp Lower dc-link voltage protection handle. + * @param spdRef Speed Reference (Hz). + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void LVP_Exec(LVP_Handle *lvp, float *spdRef, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(lvp != NULL); + MCS_ASSERT_PARAM(spdRef != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + /* According to protect level, take corresponding action. */ + switch (lvp->protLevel) { + /* level 4: disable all PWM output. */ + case PROT_LEVEL_4: + /* Disable three-phase pwm output. */ + ProtSpo_Exec(aptAddr); + *spdRef *= 0.0f; + break; + + /* level 3: derate speed reference. */ + case PROT_LEVEL_3: + *spdRef *= PROT_POW_DN2_PCT; + lvp->timer += lvp->ts; + if (lvp->timer > lvp->protLimitTime[PROT_LIMIT_TIME_2]) { + *spdRef *= PROT_POW_DN3_PCT; + } + break; + + /* level 2: derate speed reference. */ + case PROT_LEVEL_2: + *spdRef *= PROT_POW_DN1_PCT; + lvp->timer += lvp->ts; + if (lvp->timer > lvp->protLimitTime[PROT_LIMIT_TIME_1]) { + *spdRef *= PROT_POW_DN2_PCT; + } + break; + + /* level 1: derate speed reference. */ + case PROT_LEVEL_1: + lvp->timer += lvp->ts; + if (lvp->timer > lvp->protLimitTime[PROT_LIMIT_TIME_0]) { + *spdRef *= PROT_POW_DN1_PCT; + } + break; + + /* level 0: take no protection action. */ + case PROT_LEVEL_0: + break; + + default: + break; + } + return; +} + +/** + * @brief Over dc-link voltage protection recovery. + * @param ovp Over dc-link voltage protection handle. + * @param motorErrStatus Motor error status. + * @param udc DC-link voltage (V). + * @retval None. + */ +void OVP_Recy(OVP_Handle *ovp, MotorErrStatusReg *motorErrStatus, float udc) +{ + MCS_ASSERT_PARAM(ovp != NULL); + /* If not under error state, just return without any operation. */ + if (!motorErrStatus->Bit.overVoltErr) { + return; + } + + /* According to protection level, take corresponding recovery action. */ + switch (ovp->protLevel) { + /* level 4 */ + case PROT_LEVEL_4: + if (udc < ovp->protValThr[PROT_VAL_THRESHOLD_3] - ovp->recyDelta) { + ovp->recyCnt++; + if (ovp->recyCnt > ovp->recyCntLimit) { + ovp->protLevel = PROT_LEVEL_3; + ovp->recyCnt = 0; + } + } + break; + + /* level 3 */ + case PROT_LEVEL_3: + /* If the dc-link voltage is less than threshold 2, level-2 protection is restored. */ + if (udc < ovp->protValThr[PROT_VAL_THRESHOLD_2] - ovp->recyDelta) { + ovp->recyCnt++; + if (ovp->recyCnt > ovp->recyCntLimit) { + ovp->protLevel = PROT_LEVEL_2; + ovp->recyCnt = 0; + } + } + break; + + /* level 2 */ + case PROT_LEVEL_2: + /* If the dc-link voltage is less than threshold 1, level-1 protection is restored. */ + if (udc < ovp->protValThr[PROT_VAL_THRESHOLD_1] - ovp->recyDelta) { + ovp->recyCnt++; + if (ovp->recyCnt > ovp->recyCntLimit) { + ovp->protLevel = PROT_LEVEL_1; + ovp->recyCnt = 0; + } + } + break; + + /* level 1 */ + case PROT_LEVEL_1: + /* If the dc-link voltage is less than threshold 0, level-0 protection is restored. */ + if (udc < ovp->protValThr[PROT_VAL_THRESHOLD_0] - ovp->recyDelta) { + ovp->recyCnt++; + if (ovp->recyCnt > ovp->recyCntLimit) { + ovp->protLevel = PROT_LEVEL_0; + ovp->recyCnt = 0; + } + } + break; + /* level 0 Fault-free state. */ + case PROT_LEVEL_0: + motorErrStatus->Bit.overVoltErr = 0; + break; + + default: + break; + } + return; +} + +/** + * @brief Lower dc-link voltage protection recovery. + * @param lvp Lower dc-link voltage protection handle. + * @param motorErrStatus Motor error status. + * @param udc DC-link voltage (V). + * @retval None. + */ +void LVP_Recy(LVP_Handle *lvp, MotorErrStatusReg *motorErrStatus, float udc) +{ + MCS_ASSERT_PARAM(lvp != NULL); + /* If not under error state, just return without any operation. */ + if (!motorErrStatus->Bit.lowerVoltErr) { + return; + } + + /* According to protection level, take corresponding recovery action. */ + switch (lvp->protLevel) { + /* level 4 */ + case PROT_LEVEL_4: + /* If the dc-link voltage is greater than threshold 3, level-3 protection is restored. */ + if (udc > lvp->protValThr[PROT_VAL_THRESHOLD_3] + lvp->recyDelta) { + lvp->recyCnt++; + if (lvp->recyCnt > lvp->recyCntLimit) { + lvp->protLevel = PROT_LEVEL_3; + lvp->recyCnt = 0; + } + } + break; + + /* level 3 */ + case PROT_LEVEL_3: + /* If the dc-link voltage is greater than threshold 2, level-2 protection is restored. */ + if (udc > lvp->protValThr[PROT_VAL_THRESHOLD_2] + lvp->recyDelta) { + lvp->recyCnt++; + if (lvp->recyCnt > lvp->recyCntLimit) { + lvp->protLevel = PROT_LEVEL_2; + lvp->recyCnt = 0; + } + } + break; + + /* level 2 */ + case PROT_LEVEL_2: + /* If the dc-link voltage is greater than threshold 1, level-1 protection is restored. */ + if (udc > lvp->protValThr[PROT_VAL_THRESHOLD_1] + lvp->recyDelta) { + lvp->recyCnt++; + if (lvp->recyCnt > lvp->recyCntLimit) { + lvp->protLevel = PROT_LEVEL_1; + lvp->recyCnt = 0; + } + } + break; + + /* level 1 */ + case PROT_LEVEL_1: + /* If the dc-link voltage is greater than threshold 0, level-0 protection is restored. */ + if (udc > lvp->protValThr[PROT_VAL_THRESHOLD_0] + lvp->recyDelta) { + lvp->recyCnt++; + if (lvp->recyCnt > lvp->recyCntLimit) { + lvp->protLevel = PROT_LEVEL_0; + lvp->recyCnt = 0; + } + } + break; + /* level 0 Fault-free state. */ + case PROT_LEVEL_0: + motorErrStatus->Bit.lowerVoltErr = 0; + break; + + default: + break; + } + return; +} + +/** + * @brief Over dc-link voltage protection error status clear. + * @param ovp Over voltage protection handle. + * @retval None. + */ +void OVP_Clear(OVP_Handle *ovp) +{ + MCS_ASSERT_PARAM(ovp != NULL); + /* Clear the history value. */ + ovp->protCnt = 0; + ovp->protLevel = PROT_LEVEL_0; + ovp->recyCnt = 0; + ovp->timer = 0.0f; +} + +/** + * @brief Lower dc-link voltage protection error status clear. + * @param lvp Lower voltage protection handle. + * @retval None. + */ +void LVP_Clear(LVP_Handle *lvp) +{ + MCS_ASSERT_PARAM(lvp != NULL); + /* Clear the history value. */ + lvp->protCnt = 0; + lvp->protLevel = PROT_LEVEL_0; + lvp->recyCnt = 0; + lvp->timer = 0.0f; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..0435156a0add386ec4b783f4d003f4178baa2ecf --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_dc_volt_prot.h @@ -0,0 +1,69 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_dc_volt_prot.h + * @author MCU Algorithm Team + * @brief This file contains dc-link voltage protection data struct and api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McuMagicTag_MCS_DC_VOLT_PROT_H +#define McuMagicTag_MCS_DC_VOLT_PROT_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "apt_ip.h" + +typedef struct { + unsigned int protCnt; + unsigned int recyCnt; + unsigned int protCntLimit; + unsigned int recyCntLimit; + float protValThr[PROT_VAL_THRESHOLD_NUMS]; /* from low voltage level to high. */ + float protLimitTime[PROT_LIMIT_TIME_NUMS]; /* from level 3 to level 1. */ + float recyDelta; + float timer; + float ts; + PROT_Level protLevel; +} OVP_Handle; + +typedef struct { + unsigned int protCnt; + unsigned int recyCnt; + unsigned int protCntLimit; + unsigned int recyCntLimit; + float protValThr[PROT_VAL_THRESHOLD_NUMS]; /* from high voltage level to low. */ + float protLimitTime[PROT_LIMIT_TIME_NUMS]; /* from level 3 to level 1. */ + float recyDelta; + float timer; + float ts; + PROT_Level protLevel; +} LVP_Handle; + +void OVP_Init(OVP_Handle *ovp, float ts); +void OVP_Det(OVP_Handle *ovp, MotorErrStatusReg *motorErrStatus, float udc); +void OVP_Exec(OVP_Handle *ovp, float *duty, APT_RegStruct **aptAddr); +void OVP_Recy(OVP_Handle *ovp, MotorErrStatusReg *motorErrStatus, float udc); +void OVP_Clear(OVP_Handle *ovp); + +void LVP_Init(LVP_Handle *lvp, float ts); +void LVP_Det(LVP_Handle *lvp, MotorErrStatusReg *motorErrStatus, float udc); +void LVP_Exec(LVP_Handle *lvp, float *spdRef, APT_RegStruct **aptAddr); +void LVP_Recy(LVP_Handle *lvp, MotorErrStatusReg *motorErrStatus, float udc); +void LVP_Clear(LVP_Handle *lvp); + +#endif diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee4d2d240e66f7cfb0528b2d42d4c32ada0078 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.c @@ -0,0 +1,112 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_motor_stalling.c + * @author MCU Algorithm Team + * @brief This file contains motor stalling protection data struct and api definition. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_motor_stalling.h" +#include "mcs_prot_user_config.h" +#include "mcs_math.h" +#include "mcs_math_const.h" +#include "mcs_assert.h" + +/** + * @brief Initilization motor stalling protection function. + * @param stall Motor stalling handle. + * @param ts Ctrl period (s). + * @param currLimit The current amplitude that triggers fault. (A). + * @param spdLimit The speed amplitude that triggers fault. (Hz). + * @param timeLimit The threshold time that current amplitude over the limit (s). + * @retval None. + */ +void STP_Init(STP_Handle *stall, float ts, float currLimit, float spdLimit, float timeLimit) +{ + MCS_ASSERT_PARAM(stall != NULL); + MCS_ASSERT_PARAM(ts > 0.0f); + MCS_ASSERT_PARAM(currLimit > 0.0f); + MCS_ASSERT_PARAM(spdLimit > 0.0f); + MCS_ASSERT_PARAM(timeLimit > 0.0f); + /* Configuring parameters for stalling detection. */ + stall->ts = ts; + /* Current threshold and speed threshold for stalling fault. */ + stall->currAmpLimit = currLimit; + stall->spdLimit = spdLimit; + stall->timeLimit = timeLimit; + stall->timer = 0.0f; +} + +/** + * @brief Motor stalling detection. + * @param stall Motor stalling handle. + * @param motorErrStatus Motor error status. + * @param spd Speed feedback (Hz). + * @param idq Dq-axis current feedback (A). + * @retval None. + */ +void STP_Det_ByCurrSpd(STP_Handle *stall, MotorErrStatusReg *motorErrStatus, float spd, DqAxis idq) +{ + MCS_ASSERT_PARAM(stall != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(Abs(spd) >= 0.0f); + /* Calculate current amplitude. */ + float currAmp = Sqrt(idq.d * idq.d + idq.q * idq.q); + float spdAbs = Abs(spd); + /* Check if value goes over threshold for continuous cycles. */ + if (currAmp < stall->currAmpLimit || spdAbs > stall->spdLimit) { + stall->timer = 0.0f; + return; + } + /* Time accumulation. */ + if (stall->timer < stall->timeLimit) { + stall->timer += stall->ts; + return; + } + motorErrStatus->Bit.motorStalling = 1; +} + +/** + * @brief Motor stalling protection execution. + * @param motorErrStatus Motor error status. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void STP_Exec(MotorErrStatusReg *motorErrStatus, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + if (motorErrStatus->Bit.motorStalling == 0) { + return; + } + + /* Disable three-phase pwm output. */ + ProtSpo_Exec(aptAddr); + return; +} + +/** + * @brief Motor stalling protection error status clear. + * @param stall Motor stalling handle. + * @retval None. + */ +void STP_Clear(STP_Handle *stall) +{ + MCS_ASSERT_PARAM(stall != NULL); + stall->timer = 0.0f; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d1e4bed11bec0d6d73aee54de36c365588898e --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_motor_stalling.h @@ -0,0 +1,45 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_motor_stalling.h + * @author MCU Algorithm Team + * @brief This file contains motor stalling protection data struct and api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_MCS_MOTOR_STALLING_PROT_H +#define McuMagicTag_MCS_MOTOR_STALLING_PROT_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "apt_ip.h" +#include "mcs_typedef.h" + +typedef struct { + float currAmpLimit; /**< Feedback current higher than this value triggers fault. (A). */ + float spdLimit; /**< Feedback speed lower than this value triggers fault (Hz). */ + float timeLimit; /**< The threshold time that current and speed feedback over ranges (s). */ + float timer; /**< Timer to get speed and current over range time. */ + float ts; /**< Ctrl period (s). */ +} STP_Handle; + +void STP_Init(STP_Handle *stall, float ts, float currLimit, float spdLimit, float timeLimit); +void STP_Det_ByCurrSpd(STP_Handle *stall, MotorErrStatusReg *motorErrStatus, float spd, DqAxis idq); +void STP_Exec(MotorErrStatusReg *motorErrStatus, APT_RegStruct **aptAddr); +void STP_Clear(STP_Handle *stall); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.c b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..184ba4a3ac712690e4f808f1464a65c74a387b52 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.c @@ -0,0 +1,262 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_temp_prot.c + * @author MCU Algorithm Team + * @brief This file contains over temperature protection api definition. + */ + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_temp_prot.h" +#include "mcs_prot_user_config.h" +#include "mcs_assert.h" + +/** + * @brief Initilization over temperation protection function. + * @param otp Over temperature protection handle. + * @param ts Ctrl period. + * @retval None. + */ +void OTP_Init(OTP_Handle *otp, float ts) +{ + MCS_ASSERT_PARAM(otp != NULL); + MCS_ASSERT_PARAM(ts > 0.0f); + otp->ts = ts; + otp->protCntLimit = PROT_CNT_LIMIT; + otp->recyCntLimit = RECY_CNT_LIMIT; + /* Configuring the temperature protection threshold. */ + otp->protValThr[PROT_VAL_THRESHOLD_0] = PROT_OVER_IPM_TEMP_POW_DN1; + otp->protValThr[PROT_VAL_THRESHOLD_1] = PROT_OVER_IPM_TEMP_POW_DN2; + otp->protValThr[PROT_VAL_THRESHOLD_2] = PROT_OVER_IPM_TEMP_POW_DN3; + otp->protValThr[PROT_VAL_THRESHOLD_3] = PROT_OVER_IPM_TEMP_POW_OFF; + /* Configuring the protection limiting time. */ + otp->protLimitTime[PROT_LIMIT_TIME_0] = PROT_OVER_TEMP_LIMIT1_TIME_SEC; + otp->protLimitTime[PROT_LIMIT_TIME_1] = PROT_OVER_TEMP_LIMIT2_TIME_SEC; + otp->protLimitTime[PROT_LIMIT_TIME_2] = PROT_OVER_TEMP_LIMIT3_TIME_SEC; + otp->recyDelta = PROT_OVER_IPM_TEMP_RECY_DELTA; + OTP_Clear(otp); +} + +/** + * @brief Over temperatre protection detection. + * @param otp Over temperature protection handle. + * @param tempErrBit Temperature error status bit. + * @param idq DQ-axis feedback currents. + * @retval None. + */ +void OTP_Det(OTP_Handle *otp, MotorErrStatusReg *motorErrStatus, PROT_ErrBit protBit, float temp) +{ + MCS_ASSERT_PARAM(otp != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(temp > 0.0f); + /* Check if value goes over threshold for continuous cycles. */ + if (temp < otp->protValThr[PROT_VAL_THRESHOLD_0]) { + otp->protCnt = 0; + ClearBit(&motorErrStatus->all, protBit); + return; + } + + if (otp->protCnt < otp->protCntLimit) { + otp->protCnt++; + return; + } + + /* Check which protection level should be activated. */ + /* Once enter error status, error status can only be changed by recover api. */ + /* protect level: level 4. */ + if (temp >= otp->protValThr[PROT_VAL_THRESHOLD_3] && otp->protLevel < PROT_LEVEL_4) { + otp->protLevel = PROT_LEVEL_4; + SetBit(&motorErrStatus->all, protBit); + otp->protCnt = 0; + return; + } + + /* Protect level: level 3. */ + if (temp >= otp->protValThr[PROT_VAL_THRESHOLD_2] && otp->protLevel < PROT_LEVEL_3) { + otp->protLevel = PROT_LEVEL_3; + SetBit(&motorErrStatus->all, protBit); + otp->protCnt = 0; + otp->timer = 0.0f; + return; + } + + /* Protect level: level 2. */ + if (temp >= otp->protValThr[PROT_VAL_THRESHOLD_1] && otp->protLevel < PROT_LEVEL_2) { + otp->protLevel = PROT_LEVEL_2; + SetBit(&motorErrStatus->all, protBit); + otp->protCnt = 0; + otp->timer = 0.0f; + return; + } + + /* Protect level: level 1. */ + if (temp >= otp->protValThr[PROT_VAL_THRESHOLD_0] && otp->protLevel < PROT_LEVEL_1) { + otp->protLevel = PROT_LEVEL_1; + SetBit(&motorErrStatus->all, protBit); + otp->protCnt = 0; + otp->timer = 0.0f; + return; + } +} + +/** + * @brief Over temperature protection execution. + * @param otp Over temperature protection handle. + * @param spdRef Speed reference (Hz). + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +void OTP_Exec(OTP_Handle *otp, float *spdRef, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(otp != NULL); + MCS_ASSERT_PARAM(spdRef != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + /* According to protect level, take corresponding action. */ + switch (otp->protLevel) { + /* level 4: disable all PWM output. */ + case PROT_LEVEL_4: + /* Disable three-phase pwm output. */ + ProtSpo_Exec(aptAddr); + *spdRef *= 0.0f; + break; + + /* level 3: derate speed reference. */ + case PROT_LEVEL_3: + *spdRef *= PROT_POW_DN2_PCT; + otp->timer += otp->ts; + if (otp->timer > otp->protLimitTime[PROT_LIMIT_TIME_2]) { + *spdRef *= PROT_POW_DN3_PCT; + } + break; + + /* level 2: derate speed reference. */ + case PROT_LEVEL_2: + /* Reducte motor speed to level 2 */ + *spdRef *= PROT_POW_DN1_PCT; + otp->timer += otp->ts; + if (otp->timer > otp->protLimitTime[PROT_LIMIT_TIME_1]) { + *spdRef *= PROT_POW_DN2_PCT; + } + break; + + /* level 0: take no protection action. */ + case PROT_LEVEL_0: + break; + + case PROT_LEVEL_1: + /* Reducte motor speed to level 0 */ + otp->timer += otp->ts; + if (otp->timer > otp->protLimitTime[PROT_LIMIT_TIME_0]) { + /* level 1: derate speed reference. */ + *spdRef *= PROT_POW_DN1_PCT; + } + break; + + default: + break; + } + return; +} + +/** + * @brief Over temperature protection recovery. + * @param otp Over temperature protection handle. + * @param tempErrBit Temperature error status bit. + * @param temp Temperature (celsius). + * @retval None. + */ +void OTP_Recy(OTP_Handle *otp, MotorErrStatusReg *motorErrStatus, PROT_ErrBit protBit, float temp) +{ + MCS_ASSERT_PARAM(otp != NULL); + MCS_ASSERT_PARAM(motorErrStatus != NULL); + MCS_ASSERT_PARAM(temp > 0.0f); + /* If not under error state, just return without any operation. */ + if (otp->protLevel == PROT_LEVEL_0) { + motorErrStatus->all &= (~(1 >> protBit)); + return; + } + + /* According to protection level, take corresponding recovery action. */ + switch (otp->protLevel) { + /* level 4 */ + case PROT_LEVEL_4: + /* If the temperature is less than threshold 3, level-3 protection is restored. */ + if (temp < otp->protValThr[PROT_VAL_THRESHOLD_3] - otp->recyDelta) { + otp->recyCnt++; + if (otp->recyCnt > otp->recyCntLimit) { + otp->protLevel = PROT_LEVEL_3; + otp->recyCnt = 0; + } + } + break; + + /* level 3 */ + case PROT_LEVEL_3: + /* If the temperature is less than threshold 2, level-2 protection is restored. */ + if (temp < otp->protValThr[PROT_VAL_THRESHOLD_2] - otp->recyDelta) { + otp->recyCnt++; + if (otp->recyCnt > otp->recyCntLimit) { + otp->protLevel = PROT_LEVEL_2; + otp->recyCnt = 0; + } + } + break; + + /* level 2 */ + case PROT_LEVEL_2: + /* If the temperature is less than threshold 1, level-1 protection is restored. */ + if (temp < otp->protValThr[PROT_VAL_THRESHOLD_1] - otp->recyDelta) { + otp->recyCnt++; + if (otp->recyCnt > otp->recyCntLimit) { + otp->protLevel = PROT_LEVEL_1; + otp->recyCnt = 0; + } + } + break; + + /* level 1 */ + case PROT_LEVEL_1: + /* If the temperature is less than threshold 0, level-0 protection is restored. */ + if (temp < otp->protValThr[PROT_VAL_THRESHOLD_0] - otp->recyDelta) { + otp->recyCnt++; + if (otp->recyCnt > otp->recyCntLimit) { + otp->protLevel = PROT_LEVEL_0; + otp->recyCnt = 0; + } + } + break; + + default: + break; + } + return; +} + +/** + * @brief Over temperature protection error status clear. + * @param otp Over temperature protection handle. + * @retval None. + */ +void OTP_Clear(OTP_Handle *otp) +{ + MCS_ASSERT_PARAM(otp != NULL); + /* Clear the history value. */ + otp->protCnt = 0; + otp->protLevel = PROT_LEVEL_0; + otp->recyCnt = 0; + otp->timer = 0.0f; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.h b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9d99a76c19f53a78ccc1257287eccfd1fc972c --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/protection/mcs_temp_prot.h @@ -0,0 +1,49 @@ +/** + * @copyright Copyright (c) 2023, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_temp_prot.h + * @author MCU Algorithm Team + * @brief his file contains over temperature protection api declaration. + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_MCS_TEMP_PROT_H +#define McuMagicTag_MCS_TEMP_PROT_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "mcs_prot_cmm.h" +#include "apt_ip.h" + +typedef struct { + unsigned int protCnt; + unsigned int recyCnt; + unsigned int protCntLimit; + unsigned int recyCntLimit; + float protValThr[PROT_VAL_THRESHOLD_NUMS]; /* from low current level to high. */ + float protLimitTime[PROT_LIMIT_TIME_NUMS]; /* from level 3 to level 1. */ + float recyDelta; + float ts; + float timer; + PROT_Level protLevel; +} OTP_Handle; + +void OTP_Init(OTP_Handle *otp, float ts); +void OTP_Det(OTP_Handle *otp, MotorErrStatusReg *motorErrStatus, PROT_ErrBit protBit, float temp); +void OTP_Exec(OTP_Handle *otp, float *spdRef, APT_RegStruct **aptAddr); +void OTP_Recy(OTP_Handle *otp, MotorErrStatusReg *motorErrStatus, PROT_ErrBit protBit, float temp); +void OTP_Clear(OTP_Handle *otp); +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/readme.md b/vendor/others/demo/zhinenglunyi/lunyi/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8eaa717750b5d752956daa81dbff5a68f3304e92 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/readme.md @@ -0,0 +1,9 @@ +# lunyi + +**【功能描述】** ++ 通过语音控制电机的正反转、旋转一定角度吗,模拟轮椅的前后左右移动,辅助坐下站立等功能,通过按键控制电机的速度加减。 + +**【环境要求】** ++ 所有单板电源改制为演示用的12V低压,电机选用Gimbal GBM2804H-100T + + diff --git a/vendor/others/demo/zhinenglunyi/lunyi/src/lunyi.c b/vendor/others/demo/zhinenglunyi/lunyi/src/lunyi.c new file mode 100644 index 0000000000000000000000000000000000000000..1b44ff00da23f5739536c671d8669b4af9b099ff --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/src/lunyi.c @@ -0,0 +1,1114 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_motor_process.c + * @author MCU Algorithm Team + * @brief This file provides motor application. + * @details Single FOC application based on the ECMCU105H/ECBMCU201MPC board + * 1) Motor model is Gimbal GBM2804H-100T. + * 2) Select the pmsm sensorless 2shunt foc example in the sample column + of chipConfig and click Generate Code. + * 3) It's power supply must be changed to 12V. + */ +#include "main.h" +#include "mcs_user_config.h" +#include "mcs_math.h" +#include "hmi_module.h" +#include "mcs_ctlmode_config.h" +#include "mcs_prot_user.h" +#include "mcs_prot_user_config.h" +#include "mcs_math_const.h" +#include "mcs_motor_process.h" +#include "mcs_chip_config.h" +#include + + +/*------------------------------- Macro Definition -----------------------------------------------*/ +#define US_PER_MS 1000 +#define ANGLE_RANGE_ABS 65536 +#define ANGLE_360_F 65536.0f /* 0 - 65536 indicates 0 to 360. */ +#define APT_FULL_DUTY 1.0f +#define TEMP_3 3.0f +#define TEMP_15 15.0f +#define TEMP_30 30.0f +#define TEMP_45 45.0f +#define TEMP_60 60.0f +#define TEMP_RES_15 78.327f +#define TEMP_RES_30 36.776f +#define TEMP_RES_45 18.301f +#define TEMP_RES_60 9.607f +#define CNT_10 10 +#define CNT_5000 5000 +#define LEVEL_4 4 +#define MOTOR_START_DELAY 2 +#define ADC_READINIT_DELAY 1 +#define ADC_READINIT_TIMES 20 +#define ADC_TRIMVALUE_MIN 1800.0f +#define ADC_TRIMVALUE_MAX 2200.0f +/*------------------------------- Param Definition -----------------------------------------------*/ +/* Motor parameters. */ +/* Np, Rs, Ld, Lq, Psif, J, Nmax, Currmax, PPMR, zShift */ +static MOTOR_Param g_motorParam = MOTORPARAM_DEFAULTS; +static APT_RegStruct* g_apt[PHASE_MAX_NUM] = {APT_U, APT_V, APT_W}; +/* Motor control handle */ +static MTRCTRL_Handle g_mc = {0}; + +unsigned int moshi = 0 ; +unsigned int danci = 0 ; +float sudu = 30 ; +float housu = 5 ; + +/* Motor speed loop PI param. */ +static void SPDCTRL_InitWrapper(SPDCTRL_Handle *spdHandle, float ts) +{ + /* Speed loop param assignment. */ + PI_Param spdPi = { + .kp = SPD_KP, + .ki = SPD_KI, + .lowerLim = SPD_LOWERLIM, + .upperLim = SPD_UPPERLIM, + }; + /* Speed loop param init. */ + SPDCTRL_Init(spdHandle, &g_motorParam, spdPi, ts); +} + +/* Motor current Loop PI param. */ +static void CURRCTRL_InitWrapper(CURRCTRL_Handle *currHandle, DqAxis *idqRef, DqAxis *idqFbk, float ts) +{ + /* Axis-D current loop param assignment. */ + PI_Param dCurrPi = { + .kp = CURRDAXIS_KP, + .ki = CURRDAXIS_KI, + .lowerLim = CURR_LOWERLIM, + .upperLim = CURR_UPPERLIM, + }; + /* Axis-Q current loop param assignment. */ + PI_Param qCurrPi = { + .kp = CURRQAXIS_KP, + .ki = CURRQAXIS_KI, + .lowerLim = CURR_LOWERLIM, + .upperLim = CURR_UPPERLIM, + }; + /* Current loop param init. */ + CURRCTRL_Init(currHandle, &g_motorParam, idqRef, idqFbk, dCurrPi, qCurrPi, ts); +} + +/* First order smo param. */ +static void FOSMO_InitWrapper(FOSMO_Handle *fosmo, float ts) +{ + /* Smo param assignment. */ + FOSMO_Param fosmoParam = { + .gain = FOSMO_GAIN, + .lambda = FOSMO_LAMBDA, + .fcEmf = FOSMO_EMF_CUTOFF_FREQ, + .fcLpf = SPEED_FILTER_CUTOFF_FREQUENCY, + .pllBdw = FOSMO_PLL_BDW, + }; + /* Init smo param. */ + FOSMO_Init(fosmo, fosmoParam, g_motorParam, ts); +} + +/* Smo4th param. */ +static void SMO4TH_InitWrapper(SMO4TH_Handle *smo4TH) +{ + /* Smo4th param assignment. */ + SMO4TH_Param smo4thParam = { + .kd = SMO4TH_KD, + .kq = SMO4TH_KQ, + .pllBdw = SMO4TH_PLL_BDW, + .fcLpf = SMO4TH_SPD_FILTER_CUTOFF_FREQ, + }; + /* Init smo param. */ + SMO4TH_Init(smo4TH, smo4thParam, g_motorParam, CTRL_CURR_PERIOD); +} + +/*------------------------------- Function Definition -----------------------------------------------*/ +/** + * @brief Initialzer of system tick. + * @param mtrCtrl Motor control struct handle. + * @retval None. + */ +static void TimerTickInit(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->sysTickCnt = 0; + mtrCtrl->msTickNum = US_PER_MS / SYSTICK_PERIOD_US; + mtrCtrl->capChargeTickNum = (INV_CAP_CHARGE_MS * US_PER_MS / SYSTICK_PERIOD_US); +} + +/** + * @brief Init motor control task 启动电机控制任务. + * @retval None. + */ +static void TSK_Init(void) +{ + g_mc.motorStateFlag = 0; + g_mc.uartHeartDetCnt = 0; + g_mc.uartTimeStamp = 0; + g_mc.stateMachine = FSM_IDLE; + g_mc.currCtrlPeriod = CTRL_CURR_PERIOD; /* Init current controller 初始化电流控制器*/ + g_mc.aptMaxcntCmp = g_apt0.waveform.timerPeriod; + g_mc.sampleMode = DUAL_RESISTORS; + g_mc.obserType = FOC_OBSERVERTYPE_SMO4TH; /* Init foc observe mode */ + g_mc.controlMode = FOC_CONTROLMODE_SPEED; /* Init motor control mode 启动电机控制模式 */ + g_mc.adcCurrCofe = ADC_CURR_COFFI; + g_mc.spdAdjustMode = CUST_SPEED_ADJUST; + g_mc.uartConnectFlag = DISCONNECT; + // g_mc.spdCmdHz = USER_MIN_SPD_HZ; /* Motor initialization speed 电机初始化速度*/ + g_mc.spdCmdHz = 0.0f; /* Motor initialization speed 电机初始化速度*/ + g_mc.adc0Compensate = ADC0COMPENSATE; /* Phase-u current init adc shift trim value u相电流初始化adc移位微调值*/ + g_mc.adc1Compensate = ADC1COMPENSATE; /* Phase-w current init adc shift trim value w相电流初始化adc移位微调值*/ + + IF_Init(&g_mc.ifCtrl, CTRL_IF_CURR_AMP_A, USER_CURR_SLOPE, CTRL_SYSTICK_PERIOD, CTRL_CURR_PERIOD); + RMG_Init(&g_mc.spdRmg, CTRL_SYSTICK_PERIOD, USER_SPD_SLOPE); /* Init speed slope 初始速度斜率*/ + MtrParamInit(&g_mc.mtrParam, g_motorParam); + + TimerTickInit(&g_mc); + SVPWM_Init(&g_mc.sv, INV_VOLTAGE_BUS * ONE_DIV_SQRT3); + R1SVPWM_Init(&g_mc.r1Sv, INV_VOLTAGE_BUS * ONE_DIV_SQRT3, SAMPLE_POINT_SHIFT, SAMPLE_WINDOW_DUTY); + + SPDCTRL_InitWrapper(&g_mc.spdCtrl, CTRL_SYSTICK_PERIOD); + CURRCTRL_InitWrapper(&g_mc.currCtrl, &g_mc.idqRef, &g_mc.idqFbk, CTRL_CURR_PERIOD); + FOSMO_InitWrapper(&g_mc.smo, CTRL_CURR_PERIOD); + SMO4TH_InitWrapper(&g_mc.smo4th); + + STARTUP_Init(&g_mc.startup, USER_SWITCH_SPDBEGIN_HZ, USER_SWITCH_SPDBEGIN_HZ + TEMP_3); + + MotorProt_Init(&g_mc.prot); /* Init protect state comond */ + OCP_Init(&g_mc.prot.ocp, CTRL_CURR_PERIOD); + OVP_Init(&g_mc.prot.ovp, CTRL_SYSTICK_PERIOD); + LVP_Init(&g_mc.prot.lvp, CTRL_SYSTICK_PERIOD); + OTP_Init(&g_mc.prot.otp, CTRL_SYSTICK_PERIOD); + STP_Init(&g_mc.prot.stall, CTRL_SYSTICK_PERIOD, PROT_STALLING_CURR_AMP_LIMIT, + PROT_STALLING_SPD_LIMIT, PROT_STALLING_TIME_LIMIT); +} + +/** + * @brief Clear historical values of all controller before start-up. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ClearBeforeStartup(MTRCTRL_Handle *mtrCtrl) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + /* The initial angle is 0. */ + mtrCtrl->axisAngle = 0; + + mtrCtrl->spdRefHz = 0.0f; + /* The initial dq-axis reference current is 0. */ + mtrCtrl->idqRef.d = 0.0f; + mtrCtrl->idqRef.q = 0.0f; + + mtrCtrl->vdqRef.d = 0.0f; + mtrCtrl->vdqRef.q = 0.0f; + /* Clear Duty Cycle Value. The initial duty cycle is 0.5. */ + mtrCtrl->dutyUvwLeft.u = 0.5f; + mtrCtrl->dutyUvwLeft.v = 0.5f; + mtrCtrl->dutyUvwLeft.w = 0.5f; + mtrCtrl->dutyUvwRight.u = 0.5f; + mtrCtrl->dutyUvwRight.v = 0.5f; + mtrCtrl->dutyUvwRight.w = 0.5f; + + mtrCtrl->prot.motorErrStatus.all = 0x00; + + RMG_Clear(&mtrCtrl->spdRmg); /* Clear the history value of speed slope control */ + CURRCTRL_Clear(&mtrCtrl->currCtrl); + IF_Clear(&mtrCtrl->ifCtrl); + SPDCTRL_Clear(&mtrCtrl->spdCtrl); + FOSMO_Clear(&mtrCtrl->smo); + SMO4TH_Clear(&mtrCtrl->smo4th); + STARTUP_Clear(&mtrCtrl->startup); + R1SVPWM_Clear(&mtrCtrl->r1Sv); + + OTP_Clear(&mtrCtrl->prot.otp); + OCP_Clear(&mtrCtrl->prot.ocp); + OVP_Clear(&mtrCtrl->prot.ovp); + LVP_Clear(&mtrCtrl->prot.lvp); +} + +/** + * @brief To set the comparison value of the IGBT single-resistance ADC sampling trigger position.设置IGBT单电阻ADC采样触发位置的比较值 + * @param aptx The APT register struct handle. + * @param cntCmpA A Count compare reference of time-base counter. + * @param cntCmpB B Count compare reference of time-base counter. + * @param maxCntCmp Maximum Comparison Value + * @retval None. + */ +static void MCS_SetAdcCompareR1(APT_RegStruct *aptx, unsigned short cntCmpA, + unsigned short cntCmpB, unsigned short maxCntCmp) +{ + unsigned short tmp; + /* Sets the A Count compare reference of time-base counter. */ + tmp = (unsigned short)Clamp((float)(cntCmpA), (float)(maxCntCmp - 1), 1.0f); + DCL_APT_SetCounterCompare(aptx, APT_COMPARE_REFERENCE_A, tmp); + /* Sets the B Count compare reference of time-base counter. */ + tmp = (unsigned short)Clamp((float)(cntCmpB), (float)(maxCntCmp - 1), 1.0f); + DCL_APT_SetCounterCompare(aptx, APT_COMPARE_REFERENCE_B, tmp); +} + +/** + * @brief Open the three-phase lower pipe. 打开三相下管 + * @param aptAddr Three-phase APT address pointer. + * @param maxDutyCnt Max duty count. + * @retval None. + */ +static void AptTurnOnLowSidePwm(APT_RegStruct **aptAddr, unsigned short maxDutyCnt) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + MCS_ASSERT_PARAM(maxDutyCnt != 0); + unsigned short dutyCnt; + dutyCnt = (unsigned short)(maxDutyCnt * APT_FULL_DUTY); + /* Open the three-phase lower pipe */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = (APT_RegStruct *)(aptAddr[i]); + DCL_APT_SetCounterCompare(aptx, APT_COMPARE_REFERENCE_C, dutyCnt); + DCL_APT_SetCounterCompare(aptx, APT_COMPARE_REFERENCE_D, dutyCnt); + } +} + +/** + * @brief Enable three-phase pwm output.启用三相pwm输出。 + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void MotorPwmOutputEnable(APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + /* Enable three-phase pwm output */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = (APT_RegStruct *)(aptAddr[i]); + aptx->PG_OUT_FRC.BIT.rg_pga_frc_en = BASE_CFG_UNSET; + aptx->PG_OUT_FRC.BIT.rg_pgb_frc_en = BASE_CFG_UNSET; + } +} + +/** + * @brief Disable three-phase pwm output. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void MotorPwmOutputDisable(APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + /* Disable three-phase pwm output. */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = (APT_RegStruct *)(aptAddr[i]); + aptx->PG_OUT_FRC.BIT.rg_pga_frc_en = BASE_CFG_SET; + aptx->PG_OUT_FRC.BIT.rg_pgb_frc_en = BASE_CFG_SET; + DCL_APT_ForcePWMOutputLow(aptx); + } +} + +/** + * @brief Smo IF angle difference calculation. + * @param smoElecAngle Smo electrical angle. + * @param ifCtrlAngle IF control angle. + * @retval signed short angle difference. + */ +static float SmoIfAngleDiffCalc(float smoElecAngle, float ifCtrlAngle) +{ + float diff = AngleSub(smoElecAngle, ifCtrlAngle); + /* Smo IF angle difference calculation */ + return diff; +} + +/** + * @brief Construct a new mcs startupswitch object. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void MCS_StartupSwitch(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + STARTUP_Handle *startup = &mtrCtrl->startup; + DqAxis *idqRef = &mtrCtrl->idqRef; + float iftargetAmp = mtrCtrl->ifCtrl.targetAmp; + float spdRefHz = mtrCtrl->spdRefHz; + + switch (startup->stage) { + case STARTUP_STAGE_CURR: + if (mtrCtrl->ifCtrl.curAmp >= iftargetAmp) { + /* Stage change */ + idqRef->q = iftargetAmp; + startup->stage = STARTUP_STAGE_SPD; + } else { + /* current amplitude increase */ + idqRef->q = IF_CurrAmpCalc(&mtrCtrl->ifCtrl); + spdRefHz = 0.0f; + } + break; + case STARTUP_STAGE_SPD: + /* current frequency increase */ + if (Abs(spdRefHz) >= startup->spdBegin) { + /* Stage change */ + startup->stage = STARTUP_STAGE_SWITCH; + TrigVal localTrigVal; + TrigCalc(&localTrigVal, SmoIfAngleDiffCalc(mtrCtrl->smo.elecAngle, mtrCtrl->ifCtrl.angle)); + idqRef->d = 0.0f; + mtrCtrl->spdCtrl.spdPi.integral = iftargetAmp * localTrigVal.cos; + } else { + /* Speed rmg */ + spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + } + break; + + case STARTUP_STAGE_SWITCH: + /* Switch from IF to SMO */ + spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + idqRef->q = SPDCTRL_Exec(&mtrCtrl->spdCtrl, mtrCtrl->spdRefHz, mtrCtrl->smo.spdEst); + /* Transitional stage, if current reference speed > critical speed, change to next stage */ + if (spdRefHz >= startup->spdBegin + TEMP_3) { + /* Stage change */ + mtrCtrl->stateMachine = FSM_RUN; + } + break; + + default: + break; + } + mtrCtrl->spdRefHz = spdRefHz; +} + +/** + * @brief Pre-processing of motor status. + * @param statusReg System status. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void MotorStatePerProc(SysStatusReg *statusReg, volatile FsmState *stateMachine) +{ + MCS_ASSERT_PARAM(statusReg != NULL); + MCS_ASSERT_PARAM(stateMachine != NULL); + /* Get system status */ + if (SysIsError(statusReg)) { + *stateMachine = FSM_FAULT; + } + if (SysGetCmdStop(statusReg)) { + SysCmdStopClr(statusReg); + *stateMachine = FSM_STOP; + } +} + +/** + * @brief Check over current status. + * @param statusReg System status. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckOverCurrentState(SysStatusReg *statusReg, FsmState *stateMachine) +{ + MCS_ASSERT_PARAM(statusReg != NULL); + MCS_ASSERT_PARAM(stateMachine != NULL); + /* check systerm error status */ + if (SysIsError(statusReg) == false) { + *stateMachine = FSM_IDLE; + } +} + +/** + * @brief Check bootstrap capacitor charge time. + * @param mtrCtrl The motor control handle. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckBootstrpCapChargeTime(MTRCTRL_Handle *mtrCtrl, FsmState *stateMachine) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(stateMachine != NULL); + mtrCtrl->sysTickCnt++; + /* check bootstrap capacitor charge time */ + if (mtrCtrl->sysTickCnt == mtrCtrl->capChargeTickNum) { + *stateMachine = FSM_CLEAR; + } +} + +/** + * @brief Check systerm cmd start signal. + * @param mtrCtrl The motor control handle. + * @param aptAddr Three-phase APT address pointer. + * @param statusReg System status. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckSysCmdStart(MTRCTRL_Handle *mtrCtrl, + APT_RegStruct **aptAddr, + SysStatusReg *statusReg, + FsmState *stateMachine) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + MCS_ASSERT_PARAM(statusReg != NULL); + MCS_ASSERT_PARAM(stateMachine != NULL); + /* check start cmd */ + if (SysGetCmdStart(statusReg)) { + SysRunningSet(statusReg); + SysCmdStartClr(statusReg); + mtrCtrl->sysTickCnt = 0; + *stateMachine = FSM_CAP_CHARGE; + /* Preparation for charging the bootstrap capacitor. */ + AptTurnOnLowSidePwm(aptAddr, mtrCtrl->aptMaxcntCmp); + /* Out put pwm */ + MotorPwmOutputEnable(aptAddr); + } +} + +/** + * @brief System timer tick task. + * @param mtrCtrl The motor control handle. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void TSK_SystickIsr(MTRCTRL_Handle *mtrCtrl, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + SysStatusReg *statusReg = &mtrCtrl->statusReg; + FsmState *stateMachine = &mtrCtrl->stateMachine; + mtrCtrl->msTickCnt++; + /* Pre-processing of motor status. */ + MotorStatePerProc(statusReg, stateMachine); + /* statemachine */ + switch (*stateMachine) { + case FSM_IDLE: + /* Set smo estimate speed before motor start-up */ + g_mc.smo.spdEst = 0.0f; + CheckSysCmdStart(mtrCtrl, aptAddr, statusReg, stateMachine); + break; + case FSM_CAP_CHARGE: + /* Bootstrap Capacitor Charging Timing */ + CheckBootstrpCapChargeTime(mtrCtrl, stateMachine); + break; + /* Clear parameter before start */ + case FSM_CLEAR: + ClearBeforeStartup(mtrCtrl); + *stateMachine = FSM_STARTUP; + break; + case FSM_STARTUP: + MCS_StartupSwitch(mtrCtrl); + break; + case FSM_RUN: + /* Speed ramp control */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + /* Speed loop control */ + mtrCtrl->idqRef.q = SPDCTRL_Exec(&mtrCtrl->spdCtrl, mtrCtrl->spdRefHz, mtrCtrl->smo.spdEst); + break; + case FSM_STOP: + mtrCtrl->spdRefHz = 0.0f; + MotorPwmOutputDisable(aptAddr); + SysRunningClr(statusReg); + *stateMachine = FSM_IDLE; + break; + case FSM_FAULT: /* Overcurrent state */ + CheckOverCurrentState(statusReg, stateMachine); + break; + default: + break; + } +} + +/** + * @brief Read the ADC initialize bias trim value.读取ADC初始化偏置微调值 + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void TrimInitAdcShiftValue(MTRCTRL_Handle *mtrCtrl) +{ + float adc0SampleTemp = 0.0f; /* Current bias value for temp store */ + float adc1SampleTemp = 0.0f; + float adc0TempSum = 0.0f; + float adc1TempSum = 0.0f; /* Current bias sum value for 20 times */ + float adcSampleTimes = 0.0f; /* ADC sample times */ + for (int i = 0; i < ADC_READINIT_TIMES; i++) { + adc0SampleTemp = (float)HAL_ADC_GetConvResult(&ADCU_HANDLE, ADCUSOCNUM); + adc1SampleTemp = (float)HAL_ADC_GetConvResult(&ADCW_HANDLE, ADCWSOCNUM); + BASE_FUNC_DELAY_US(200); /* 200 is delay count, delay 200us triger adc sampling */ + if (adc0SampleTemp > 1000.0f && adc1SampleTemp > 1000.0f) { + adcSampleTimes++; + adc0TempSum += adc0SampleTemp; + adc1TempSum += adc1SampleTemp; + } + } + adc0SampleTemp = adc0TempSum / adcSampleTimes; + adc1SampleTemp = adc1TempSum / adcSampleTimes; + /* Force convert to float */ + mtrCtrl->adc0Compensate = (float) adc0SampleTemp; + mtrCtrl->adc1Compensate = (float) adc1SampleTemp; + /* The normal value scope: 1800 < adc0Compensate < 2200 */ + if(g_mc.adc0Compensate < ADC_TRIMVALUE_MIN || g_mc.adc0Compensate > ADC_TRIMVALUE_MAX \ + || g_mc.adc1Compensate < ADC_TRIMVALUE_MIN || g_mc.adc1Compensate > ADC_TRIMVALUE_MAX) { + DBG_PRINTF("ADC trim value error,please reset!"); + HAL_GPIO_SetValue(&LED2_HANDLE, LED2_PIN, GPIO_LOW_LEVEL); + } + adcSampleTimes = 0; + adc0TempSum = 0; + adc1TempSum = 0; +} + +/** + * @brief Read the ADC current sampling value 读取ADC电流采样值. + * @param CurrUvw Three-phase current 三相电流. + * @retval None. + */ +static void ReadCurrUvw(UvwAxis *CurrUvw) +{ + MCS_ASSERT_PARAM(CurrUvw != NULL); + float adc0 = (float)HAL_ADC_GetConvResult(&ADCU_HANDLE, ADCUSOCNUM); + float adc1 = (float)HAL_ADC_GetConvResult(&ADCW_HANDLE, ADCWSOCNUM); + /* Convert adc sample value to current value */ + CurrUvw->u = -(adc0 - g_mc.adc0Compensate) * g_mc.adcCurrCofe; + CurrUvw->w = -(adc1 - g_mc.adc1Compensate) * g_mc.adcCurrCofe; + CurrUvw->v = -CurrUvw->u - CurrUvw->w; +} + +/** + * @brief Setting the APT Output Duty Cycle.设置APT输出占空比 + * @param aptx APT register base address. + * @param leftDuty Left duty cycle. + * @param rightDuty Right duty cycle. + * @retval None. + */ +static void SetPwmDuty(APT_Handle *aptx, float leftDuty, float rightDuty) +{ + MCS_ASSERT_PARAM(aptx != NULL); + MCS_ASSERT_PARAM(leftDuty > 0); + MCS_ASSERT_PARAM(rightDuty > 0); + unsigned short maxPeriodCnt = aptx->waveform.timerPeriod; + unsigned short cntCmpLeftEdge = (unsigned short)(leftDuty * maxPeriodCnt); + unsigned short cntCmpRightEdge = (unsigned short)(rightDuty * maxPeriodCnt); + /* avoid overflowing */ + cntCmpLeftEdge = (cntCmpLeftEdge > maxPeriodCnt) ? maxPeriodCnt : cntCmpLeftEdge; + cntCmpRightEdge = (cntCmpRightEdge > maxPeriodCnt) ? maxPeriodCnt : cntCmpRightEdge; + HAL_APT_SetPWMDuty(aptx, cntCmpLeftEdge, cntCmpRightEdge); +} + +/** + * @brief Duty Cycle Setting 占空比设置. + * @param dutyUvwLeft Three-phase left duty cycle. + * @param dutyUvwRight Three-phase right duty cycle. + * @retval None. + */ +static void SetPwmDutyCp(UvwAxis *dutyUvwLeft, UvwAxis *dutyUvwRight) +{ + MCS_ASSERT_PARAM(dutyUvwLeft != NULL); + MCS_ASSERT_PARAM(dutyUvwRight != NULL); + /* Setting the Three-Phase Duty Cycle */ + SetPwmDuty(&g_apt0, dutyUvwLeft->u, dutyUvwRight->u); + SetPwmDuty(&g_apt1, dutyUvwLeft->v, dutyUvwRight->v); + SetPwmDuty(&g_apt2, dutyUvwLeft->w, dutyUvwRight->w); +} + +/** + * @brief To set the ADC sampling trigger comparison value 设置ADC采样触发比较值. + * @param cntCmpSOCA Soca Compare Count Value. + * @param cntCmpSOCB Socb Compare Count Value. + * @retval None. + */ +static void SetADCTriggerTime(unsigned short cntCmpSOCA, unsigned short cntCmpSOCB) +{ + MCS_SetAdcCompareR1(g_apt[PHASE_U], cntCmpSOCA, cntCmpSOCB, g_mc.aptMaxcntCmp); +} + +/** + * @brief Temprature table, the temprature detect range is 15 ~ 60 degree. + * @param tempResisValue Temperature sensor resistance. + * @retval None. + */ +static float TempTable(float tempResisValue) +{ + float boardTemp; + /* Temperatures between 15 and 30. */ + if (tempResisValue > TEMP_RES_30 && tempResisValue <= TEMP_RES_15) { + boardTemp = TEMP_15 + (TEMP_30 - TEMP_15) * (TEMP_RES_15 - tempResisValue) / (TEMP_RES_15 - TEMP_RES_30); + } else if (tempResisValue > TEMP_RES_45 && tempResisValue <= TEMP_RES_30) { /* Temperature between 30 and 45. */ + boardTemp = TEMP_30 + (TEMP_45 - TEMP_30) * (TEMP_RES_30 - tempResisValue) / (TEMP_RES_30 - TEMP_RES_45); + } else if (tempResisValue > TEMP_RES_60 && tempResisValue <= TEMP_RES_45) { /* Temperature between 45 and 50. */ + boardTemp = TEMP_45 + (TEMP_60 - TEMP_45) * (TEMP_RES_45 - tempResisValue) / (TEMP_RES_45 - TEMP_RES_60); + } else if (tempResisValue <= TEMP_RES_60) { + boardTemp = TEMP_60; /* If temperature is over 60, set temperature as 60. */ + } else if (tempResisValue >= TEMP_RES_15) { + boardTemp = TEMP_15; /* If temperature is lower 15, set temperature as 15. */ + } + return boardTemp; +} + +/** + * @brief Read power board temperature and udc.读取电源板温度和电压 + * @retval None. + */ +static void ReadBoardTempAndUdc(void) +{ + HAL_ADC_SoftTrigSample(&ADCRESIS_HANDLE, ADCRESISSOCNUM); + HAL_ADC_SoftTrigSample(&ADCUDC_HANDLE, ADCUDCSOCNUM); + BASE_FUNC_DELAY_US(CNT_10); /* Delay 10 us. */ + /* Force convert to float type. */ + float resisAdcValue = (float)HAL_ADC_GetConvResult(&ADCRESIS_HANDLE, ADCRESISSOCNUM); + /* 10 / (x + 10) * 3.3 = resisAdcValue / 4096 * 3.3, x is resisValue, 10kohm is resistor divider value. */ + float resisValue = (4096.0f * 10.0f - 10.0f * resisAdcValue) / resisAdcValue; + g_mc.powerBoardTemp = TempTable(resisValue); + g_mc.udc = ((float)HAL_ADC_GetConvResult(&ADCUDC_HANDLE, ADCUDCSOCNUM)) * ADC_UDC_COFFI; +} + +/** + * @brief Execut abnormal feedback speed protect motion. + * @retval None. + */ +static void SpdFbkErrorProt_Exec(void) +{ + if (g_mc.prot.motorErrStatus.Bit.motorStalling == 0 && + g_mc.prot.motorErrStatus.Bit.overVoltErr == 0 && + g_mc.prot.motorErrStatus.Bit.lowerVoltErr == 0 && + g_mc.prot.motorErrStatus.Bit.overIpmTempErr == 0 && + g_mc.prot.motorErrStatus.Bit.overCurrErr == 0) { + g_mc.prot.motorErrStatus.Bit.revRotErr = 1; + /* If revRotErr, execute protect motion. */ + ProtSpo_Exec(g_apt); + } +} + +/** + * @brief Execut nan data protect motion. + * @retval None. + */ +static void NanDataDetect(void) +{ + static short errorSpdStatus = 0; + /* Detect the nan observer speed or current value. */ + if (isnan(g_mc.smo.spdEst) || isnan(g_mc.idqRef.q)) { + errorSpdStatus++; + } else { + errorSpdStatus = 0; + } + /* If the data is nan & continuous counting value is over 500 times, execute protect motion. + the detect time is 500 * 500us = 250ms. */ + if (errorSpdStatus >= 500) { + errorSpdStatus = 0; + SpdFbkErrorProt_Exec(); + } +} + +/** + * @brief Check abnormal feedback speed检查反馈速度异常. + * @retval None. + */ +static void CheckSpdFbkStatus(void) +{ + static short errorCurrStatus = 0; + static short errorDeltaSpdStatus = 0; + NanDataDetect(); + if (g_mc.stateMachine == FSM_RUN) { + /* Detect the abnormal idq feedback current. */ + if (Abs(g_mc.idqRef.q - g_mc.idqFbk.q) >= CTRL_IF_CURR_AMP_A) { + errorCurrStatus++; + } else { + errorCurrStatus = 0; + } + /* Detect the abnormal feedback speed, the normal speed is > 0, if smo.spdEst < -10 && + delta speed error > USER_MIN_SPD_HZ + 10.0f at FSM_RUN stage, set the motor motion as error */ + if (g_mc.smo.spdEst < -10.0f && (g_mc.spdRefHz - g_mc.smo.spdEst > USER_MIN_SPD_HZ + 10.0f)) { + errorDeltaSpdStatus++; + } + } + /* Execute protect motion if count over 500 times, this error status caused by abnormal speed + or cabnormal urrent feedback, the detect time is 500 * 500us = 250ms. */ + if (errorCurrStatus >= 500) { + errorCurrStatus = 0; + SpdFbkErrorProt_Exec(); + } + /* This error statu caused by motor stalling, the detect time is 2 * 500us = 1ms. */ + if (errorDeltaSpdStatus >= 2) { + errorDeltaSpdStatus = 0; + g_mc.prot.motorErrStatus.Bit.motorStalling = 1; + } +} + +/** + * @brief Check Potentiometer Value callback function检查电位计值回调功能. + * @param param The TIMER_Handle. + * @retval None. + */ +void CheckPotentiometerValueCallback(void *param) +{ + MCS_ASSERT_PARAM(param != NULL); + BASE_FUNC_UNUSED(param); + + if(HAL_GPIO_GetPinValue(&g_gpio4, GPIO_PIN_4)==GPIO_HIGH_LEVEL){ + BASE_FUNC_DELAY_MS(30); + if(HAL_GPIO_GetPinValue(&g_gpio4, GPIO_PIN_4)==GPIO_HIGH_LEVEL){ + moshi = 1 ; + } + } + + else if (HAL_GPIO_GetPinValue(&g_gpio2, GPIO_PIN_0)==GPIO_LOW_LEVEL){ + BASE_FUNC_DELAY_MS(30); + if(HAL_GPIO_GetPinValue(&g_gpio2, GPIO_PIN_0)==GPIO_LOW_LEVEL){ + moshi = 2 ; + } + } + else if (HAL_GPIO_GetPinValue(&g_gpio4, GPIO_PIN_3)==GPIO_HIGH_LEVEL){ + BASE_FUNC_DELAY_MS(30); + if(HAL_GPIO_GetPinValue(&g_gpio4, GPIO_PIN_3)==GPIO_HIGH_LEVEL){ + moshi = 3 ; + } + } + else{ + moshi = 0 ; + } + + + + + +} + +/** + * @brief System timer ISR for Motor Statemachine CallBack function.用于电机状态机回叫功能的系统定时器ISR + * @param param The systick timer handle. + * @retval None. + */ +void MotorStatemachineCallBack(void *param) +{ + /* Verify Parameters 验证参数*/ + MCS_ASSERT_PARAM(param != NULL); + BASE_FUNC_UNUSED(param); + /* Read power board temprature and voltage. 读取电源板温度和电压*/ + ReadBoardTempAndUdc(); + /* Motor speed loop state machine. 电机速度回路状态机*/ + TSK_SystickIsr(&g_mc, g_apt); + + /* Motor error speed feedback check. 电机错误速度反馈检查。*/ + CheckSpdFbkStatus(); + /* Motor stalling detect.电机失速检测 */ + STP_Det_ByCurrSpd(&g_mc.prot.stall, &g_mc.prot.motorErrStatus, g_mc.smo.spdEst, g_mc.idqFbk); + STP_Exec(&g_mc.prot.motorErrStatus, g_apt); + + /* Motor over voltage detect. 电机过电压检测*/ + OVP_Det(&g_mc.prot.ovp, &g_mc.prot.motorErrStatus, g_mc.udc); + OVP_Exec(&g_mc.prot.ovp, &g_mc.spdRefHz, g_apt); + OVP_Recy(&g_mc.prot.ovp, &g_mc.prot.motorErrStatus, g_mc.udc); + /* Motor lower voltage detect. 电机低电压检测。*/ + LVP_Det(&g_mc.prot.lvp, &g_mc.prot.motorErrStatus, g_mc.udc); + LVP_Exec(&g_mc.prot.lvp, &g_mc.spdRefHz, g_apt); + LVP_Recy(&g_mc.prot.lvp, &g_mc.prot.motorErrStatus, g_mc.udc); + /* Power board over temperature detect.电源板温度过高检测。 */ + OTP_Det(&g_mc.prot.otp, &g_mc.prot.motorErrStatus, OTP_IPM_ERR_BIT, g_mc.powerBoardTemp); + OTP_Exec(&g_mc.prot.otp, &g_mc.spdRefHz, g_apt); + OTP_Recy(&g_mc.prot.otp, &g_mc.prot.motorErrStatus, OTP_IPM_ERR_BIT, g_mc.powerBoardTemp); + + /* If protect level == 4, set motor state as stop. 如果保护级别==4,则将电机状态设置为停止*/ + if (g_mc.prot.ovp.protLevel == LEVEL_4 || g_mc.prot.lvp.protLevel == LEVEL_4 \ + || g_mc.prot.otp.protLevel == LEVEL_4) { + SysCmdStopSet(&g_mc.statusReg); + } +} + +/** + * @brief The carrier ISR wrapper function. + * @param aptHandle The APT handle. + * @retval None. + */ +void MotorCarrierProcessCallback(void *aptHandle) +{ + MCS_ASSERT_PARAM(aptHandle != NULL); + BASE_FUNC_UNUSED(aptHandle); + /* the carrierprocess of motor */ + MCS_CarrierProcess(&g_mc); + /* Over current protect */ + if (g_mc.stateMachine == FSM_RUN || g_mc.stateMachine == FSM_STARTUP) { + OCP_Det(&g_mc.prot.ocp, &g_mc.prot.motorErrStatus, g_mc.idqFbk); + OCP_Exec(&g_mc.prot.ocp, &g_mc.idqFbk, g_apt); /* Execute over current protect motion */ + if (g_mc.prot.ocp.protLevel < LEVEL_4) { + OCP_Recy(&g_mc.prot.ocp, &g_mc.prot.motorErrStatus); + } + } +} + +/** + * @brief Event interrupt callback function of APT module. + * @param para APT module handle. + * @retval None. + */ +void MotorSysErrCallback(void *para) +{ + MCS_ASSERT_PARAM(para != NULL); + APT_Handle *handle = (APT_Handle *)para; + /* The IPM overcurrent triggers and disables the three-phase PWM output. */ + MotorPwmOutputDisable(g_apt); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_apt[PHASE_U], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_apt[PHASE_V], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_apt[PHASE_W], APT_OC_COMBINE_EVENT_A1); + /* Status setting error */ + SysErrorSet(&g_mc.statusReg); + DBG_PRINTF("APT error! \r\n"); + HAL_GPIO_SetValue(&LED2_HANDLE, LED2_PIN, GPIO_LOW_LEVEL); + BASE_FUNC_UNUSED(handle); +} + +/** + * @brief Init motor controller's data structure. + * @retval None. + */ +static void InitSoftware(void) +{ + /* Initializing motor control param 正在初始化电机控制参数*/ + TSK_Init(); + /* Read phase-uvw current 读取相位uvw电流*/ + g_mc.readCurrUvwCb = ReadCurrUvw; + g_mc.setPwmDutyCb = SetPwmDutyCp; + g_mc.setADCTriggerTimeCb = SetADCTriggerTime; +} + +/** + * @brief Config the master APT. + * @param aptx The master APT handle. + * @retval None. + */ +static void AptMasterSet(APT_Handle *aptx) +{ + MCS_ASSERT_PARAM(aptx != NULL); + /* Config the master APT. */ + HAL_APT_MasterSyncInit(aptx, APT_SYNC_OUT_ON_CNTR_ZERO); +} + +/** + * @brief Config the slave APT. + * @param aptx The slave APT handle. + * @retval None. + */ +static void AptSalveSet(APT_Handle *aptx) +{ + MCS_ASSERT_PARAM(aptx != NULL); + APT_SlaveSyncIn slave; + /* Config the slave APT. */ + slave.divPhase = 0; + slave.cntPhase = 0; + slave.syncCntMode = APT_COUNT_MODE_AFTER_SYNC_UP; + slave.syncInSrc = APT_SYNC_IN_SRC; + slave.cntrSyncSrc = APT_CNTR_SYNC_SRC_SYNCIN; + HAL_APT_SlaveSyncInit(aptx, &slave); +} +/** + * @brief Configuring Master and Slave APTs. + * @retval None. + */ +static void AptMasterSalveSet(void) +{ + /* motor APT master/slave synchronization 电机APT主/从同步*/ + AptMasterSet(&g_apt0); + AptSalveSet(&g_apt1); + AptSalveSet(&g_apt2); +} + +/** + * @brief Config the KEY func. + * @param handle The GPIO handle. + * @retval None. + */ +static KEY_State Key_StateRead(GPIO_Handle *handle) +{ + if (HAL_GPIO_GetPinValue(handle, handle->pins) == 0) { + BASE_FUNC_DELAY_MS(30); /* delay 30ms for deshake */ + if (HAL_GPIO_GetPinValue(handle, handle->pins) == 0) { + while (HAL_GPIO_GetPinValue(handle, handle->pins) == 0) { + } + return KEY_DOWN; + } + } + return KEY_UP; +} + +/** + * @brief Control motor start and stop state by key func.通过按键功能控制电机启动和停止状态 + * @param param The GPIO handle. + * @retval None. + */ +void MotorStartStopKeyCallback(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + if (Key_StateRead(handle) == KEY_DOWN) { + if (g_mc.motorStateFlag == 0) { /* start motor */ + g_mc.motorStateFlag = 1; + SysCmdStartSet(&g_mc.statusReg); + } else if (g_mc.motorStateFlag == 1) { /* stop motor */ + g_mc.motorStateFlag = 0; + SysCmdStopSet(&g_mc.statusReg); + } + } +} + + +void tingzhi(void) +{ + SysCmdStopSet(&g_mc.statusReg); + g_mc.spdCmdHz=0.0f; + HMI_Process_Tx(&g_mc); + SysCmdStartSet(&g_mc.statusReg); +} + +void zhengzhuan(float sudu) +{ + g_mc.spdCmdHz=sudu; + HMI_Process_Tx(&g_mc); + // BASE_FUNC_DELAY_MS(3000); + // SysCmdStopSet(&g_mc.statusReg); + // g_mc.spdCmdHz=0.0f; + // HMI_Process_Tx(&g_mc); + // SysCmdStartSet(&g_mc.statusReg); + +} + +void fanzhuan(float sudu) +{ + g_mc.spdCmdHz=-sudu; + HMI_Process_Tx(&g_mc); + // BASE_FUNC_DELAY_MS(3000); + // SysCmdStopSet(&g_mc.statusReg); + // g_mc.spdCmdHz=0.0f; + // HMI_Process_Tx(&g_mc); + // SysCmdStartSet(&g_mc.statusReg); +} + +void jiaodu(void) +{ + g_mc.spdCmdHz=7; + HMI_Process_Tx(&g_mc); + BASE_FUNC_DELAY_MS(750); + SysCmdStopSet(&g_mc.statusReg); + g_mc.spdCmdHz=0.0f; + HMI_Process_Tx(&g_mc); + SysCmdStartSet(&g_mc.statusReg); +} + + +void GPIO5_0_CallbackFunc(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + GPIO_ASSERT_PARAM(handle != NULL); + DBG_PRINTF("123\r\n"); + if(moshi == 1 && sudu<180){ + sudu = sudu + 10 ; + zhengzhuan(sudu); + } + if(moshi == 2 && housu<25){ + housu = housu + 5 ; + fanzhuan(housu); + } + + +} + +void GPIO2_1_CallbackFunc(void *param) +{ + GPIO_Handle *handle = (GPIO_Handle *)param; + GPIO_ASSERT_PARAM(handle != NULL); + DBG_PRINTF("456\r\n"); + if(moshi == 1 && sudu>=10){ + sudu = sudu - 10 ; + zhengzhuan(sudu); + } + if(moshi == 2 && housu>=5){ + housu = housu - 5 ; + fanzhuan(housu); + } + +} + + +/** + * @brief User application main entry function. + * @retval BSP_OK. + */ +int MotorMainProcess(void) +{ + unsigned int tickNum1Ms = 2; /* 1ms tick */ + static unsigned int tickCnt1Ms = 0; + unsigned int tickNum500Ms = 1000; /* 500ms tick */ + static unsigned int tickCnt500Ms = 0; + SystemInit(); + HMI_Init(); /* Init uart interrupt */ + HAL_TIMER_Start(&g_timer0); + HAL_TIMER_Start(&g_timer1); + + AptMasterSalveSet(); + /* Disable PWM output before startup. 启动前禁用PWM输出 */ + MotorPwmOutputDisable(g_apt); + /* Software initialization. 软件初始化 */ + InitSoftware(); + /* Start the PWM clock. */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + /* System Timer clock. */ + BASE_FUNC_DELAY_MS(ADC_READINIT_DELAY); + TrimInitAdcShiftValue(&g_mc); + BASE_FUNC_DELAY_MS(MOTOR_START_DELAY); + // g_mc.motorStateFlag = 1; + + while (1) { + while(g_mc.motorStateFlag == 1){ + + + /* Cycling send data to host 循环向主机发送数据 */ + // HMI_Process_Tx(&g_mc); + if (g_mc.msTickCnt - tickCnt1Ms >= tickNum1Ms) { + tickCnt1Ms = g_mc.msTickCnt; + /* User Code 1ms Event 用户代码1ms事件*/ + HMI_Process_Rx(&g_mc); + /* User Code 1ms Event */ + } + + if (g_mc.msTickCnt - tickCnt500Ms >= tickNum500Ms) { + if (SysIsError(&g_mc.statusReg) != true) { + /* LED toggle in normal status. */ + HAL_GPIO_TogglePin(&LED1_HANDLE, LED1_PIN); + } + tickCnt500Ms = g_mc.msTickCnt; + } + + + if(danci != moshi){ + + danci = moshi; + + + switch(moshi){ + + case 1 : + tingzhi(); + zhengzhuan(sudu); + break; + case 2 : + tingzhi(); + fanzhuan(housu); + break; + case 3 : + tingzhi(); + jiaodu(); + break; + case 0 : + tingzhi(); + break; + + default: + DBG_PRINTF("mo shi xuan ce\r\n"); + } + } + + } + + + } + return 0; +} diff --git a/vendor/others/demo/zhinenglunyi/lunyi/src/mcs_carrier.c b/vendor/others/demo/zhinenglunyi/lunyi/src/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..9fc8afac32ecb5810db6758fb6acbca42a4c0f69 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/src/mcs_carrier.c @@ -0,0 +1,144 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file mcs_carrier.c + * @author MCU Algorithm Team + * @brief This file provides carrier interrupt application for motor control. + */ + +#include "mcs_carrier.h" +#include "mcs_math.h" +#include "typedefs.h" +#include "mcs_assert.h" +#include "mcs_user_config.h" +#include "mcs_ctlmode_config.h" + +/** + * @brief Synchronous rotation coordinate system angle. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void MCS_SyncCoorAngle(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + /* Synchronous rotation coordinate system angle. */ + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + /* Current ramp angle is 0. */ + if (mtrCtrl->startup.stage == STARTUP_STAGE_CURR) { + mtrCtrl->axisAngle = 0; + } else if (mtrCtrl->startup.stage == STARTUP_STAGE_SPD) { /* IF control phase angle self-addition. */ + mtrCtrl->axisAngle = IF_CurrAngleCalc(&mtrCtrl->ifCtrl, mtrCtrl->spdRefHz); + } else if (mtrCtrl->startup.stage == STARTUP_STAGE_SWITCH) { /* Switch Angle */ + mtrCtrl->axisAngle = mtrCtrl->smo.elecAngle; + } + break; + + case FSM_RUN: + mtrCtrl->axisAngle = mtrCtrl->smo.elecAngle; + break; + + default: + mtrCtrl->axisAngle = 0; + break; + } +} + +/** + * @brief PWM waveform setting and sampling point setting for a single resistors and dual resistors. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void MCS_PwmAdcSet(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + SampleMode sampleMode = mtrCtrl->sampleMode; + /* Set the duty cycle according to the sampling mode. */ + if (sampleMode == DUAL_RESISTORS) { + SVPWM_Exec(&mtrCtrl->sv, &mtrCtrl->vabRef, &mtrCtrl->dutyUvw); + mtrCtrl->setPwmDutyCb(&mtrCtrl->dutyUvw, &mtrCtrl->dutyUvw); + } else if (sampleMode == SINGLE_RESISTOR) { + R1SVPWM_Exec(&mtrCtrl->r1Sv, &mtrCtrl->vabRef, &mtrCtrl->dutyUvwLeft, &mtrCtrl->dutyUvwRight); + mtrCtrl->setPwmDutyCb(&mtrCtrl->dutyUvwLeft, &mtrCtrl->dutyUvwRight); + /* The ADC sampling point position needs to be set based on the phase shift of a single resistors. */ + mtrCtrl->setADCTriggerTimeCb(mtrCtrl->r1Sv.samplePoint[0] * mtrCtrl->aptMaxcntCmp, \ + mtrCtrl->r1Sv.samplePoint[1] * mtrCtrl->aptMaxcntCmp); + } +} + +/** + * @brief Carrier interrupt function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + UvwAxis *currUvw = &mtrCtrl->currUvw; + AlbeAxis *currAlbe = &mtrCtrl->iabFbk; + AlbeAxis *vab = &mtrCtrl->vabRef; + SampleMode sampleMode = mtrCtrl->sampleMode; + /* sample mode verify */ + if (sampleMode > SINGLE_RESISTOR || mtrCtrl->setADCTriggerTimeCb == NULL) { + return; + } + /* param verify */ + if (mtrCtrl->setPwmDutyCb == NULL || mtrCtrl->readCurrUvwCb == NULL) { + return; + } + /* Read the three-phase current value. */ + mtrCtrl->readCurrUvwCb(currUvw); + /* Clark Calc */ + ClarkeCalc(currUvw, currAlbe); + /* Smo observation */ + if (mtrCtrl->obserType == FOC_OBSERVERTYPE_SMO1TH) { + /* Smo observation */ + FOSMO_Exec(&mtrCtrl->smo, currAlbe, vab, mtrCtrl->spdRefHz); + } else if (mtrCtrl->obserType == FOC_OBSERVERTYPE_SMO4TH) { + /* Smo4th observation */ + SMO4TH_Exec(&mtrCtrl->smo4th, currAlbe, vab); + mtrCtrl->smo.spdEst = mtrCtrl->smo4th.spdEst; + mtrCtrl->smo.elecAngle = mtrCtrl->smo4th.elecAngle; + } + /* Synchronization angle */ + MCS_SyncCoorAngle(mtrCtrl); + + /* Park transformation */ + ParkCalc(currAlbe, mtrCtrl->axisAngle, &mtrCtrl->idqFbk); + + /* statemachine */ + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + case FSM_RUN: + CURRCTRL_Exec(&mtrCtrl->currCtrl, &mtrCtrl->vdqRef, mtrCtrl->smo.spdEst, 0); + InvParkCalc(&mtrCtrl->vdqRef, mtrCtrl->axisAngle, vab); + MCS_PwmAdcSet(mtrCtrl); + break; + + case FSM_CAP_CHARGE: + case FSM_CLEAR: + case FSM_IDLE: + mtrCtrl->smo4th.spdEst = 0.0f; + break; + + default: + vab->alpha = 0.0f; + vab->beta = 0.0f; + MCS_PwmAdcSet(mtrCtrl); + break; + } +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.c b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.c new file mode 100644 index 0000000000000000000000000000000000000000..9836dc765691d2163bf75a2356653eb8eecf5981 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.c @@ -0,0 +1,718 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file cust_process.c + * @author MCU Algorithm Team + * @brief This file provides functions declaration of cust process interface. + */ + +#include "cust_process.h" +#include "mcs_ctlmode_config.h" +#include "mcs_math_const.h" +#include "mcs_user_config.h" +#include "mcs_assert.h" +#include "main.h" +#include "uart_module.h" +#include "mcs_mtr_param.h" +/* Macro definitions --------------------------------------------------------------------------- */ +/* Constant value. */ +#define CONST_VALUE_60 60.0f /* Constant value 60. */ +#define CONST_VALUE_DIV_1000 0.001f /* Constant value 1/1000. */ + +/* Data array index. */ +#define DATA_SEGMENT_ONE 0 /* First element of the data segment */ +#define DATA_SEGMENT_TWO 1 /* Second element of the data segment */ +#define DATA_SEGMENT_THREE 2 /* Third element of the data segment */ +#define DATA_SEGMENT_FOUR 3 /* Fourth element of the data segment */ +#define CUSTACKCODELEN 10 /* Ack code length */ + +/* Command code. */ +#define SET_PID_KP 0x01 /* Set Pid Kp Command Params */ +#define SET_PID_KI 0x02 /* Set Pid Ki Command Params */ +#define SET_PID_LIMIT 0x03 /* Set Pid limit Command Params */ + +#define SET_SMO1TH_PLL_BDW 0x01 /* Set Smo1th Pll BandWidth Command Params */ +#define SET_SMO1TH_SPDFLITER_FC 0x02 /* Set Smo1th Fc Command Params */ +#define SET_SMO1TH_FILCOMPANGLE 0x03 /* Set Smo1th FillComp Command Params */ + +#define SET_SMO4TH_KD 0x01 /* Set Smo4th Kd Command Params */ +#define SET_SMO4TH_KP 0x02 /* Set Smo4th Kq Command Params */ + +#define SET_SPD_COMMAND_HZ 0x01 /* Set Target Speed Command Params */ +#define SET_SPD_RMG_SLOPE 0x02 /* Set Speed Slope Command Params */ + +#define SET_MAX_ELEC_SPD 0x01 /* Set Max Motor Speed Command Params */ +#define SET_MOTOR_NUM_OF_PAIRS 0x02 /* Set Motor Command Params */ + +#define SET_MOTOR_RES_OF_STATOR 0x01 /* Set Motor Res Command Params */ +#define SET_MOTOR_DAXIS_INDUCTANCE 0x02 /* Set Motor Daxis Inductance Command Params */ +#define SET_MOTOR_QAXIS_INDUCTANCE 0x03 /* Set Motor Qaxis Inductance Command Params */ + +#define SET_SVPWM_VOLTAGE_PER_UNIT 0x01 /* Set Svpwm Voltage Params */ +#define SET_ADC_CURRENT_SAMPLE_COFE 0x02 /* Set Adc coffe Params */ +#define SET_CURRENT_LOOP_CONTROL_PERIOD 0x03 /* Set Current loop period Command Params */ + +#define SET_IF_TARGET_CURRENT_VALUE 0x01 /* Set If Target Params */ +#define SET_INCREMENT_OF_IF_CURRENT 0x02 /* Set If Step Command Params */ +#define SET_SPEED_RING_BEGIN_SPEED 0x03 /* Set If to Smo Start Speed Command Params */ + +static unsigned char ackCode = 0; +static unsigned char g_uartTxBuf[CUSTACKCODELEN] = {0}; + +/** + * @brief Set observer type. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetObserverType(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + if (funcCode == FOC_OBSERVERTYPE_SMO1TH) { + ackCode = 0X01; + mtrCtrl->obserType = FOC_OBSERVERTYPE_SMO1TH; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->obserType); + } else if (funcCode == FOC_OBSERVERTYPE_SMO4TH) { + ackCode = 0X02; + mtrCtrl->obserType = FOC_OBSERVERTYPE_SMO4TH; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->obserType); + } +} + +/** + * @brief Set pid parameter ack code. + * @param funcCode Received data funccode. + */ +static unsigned char SetPidAckCode(int funcCode) +{ + switch (funcCode) { + /* Set current loop D-Axis PID parameter ack code. */ + case FOC_CURDAXISPID_PARAMS: + ackCode = 0xE0; + break; + /* Set current loop Q-Axis PID parameter ack code. */ + case FOC_CURQAXISPID_PARAMS: + ackCode = 0xE3; + break; + /* Set speed loop PID parameter ack code. */ + case FOC_SPDPID_PARAMS: + ackCode = 0xE6; + break; + default: + break; + } + return ackCode; +} + +/** + * @brief Set pid parameters. + * @param pidHandle The pid control handle. + * @param rxData Receive buffer + */ +static void SetPidParams(PID_Handle *pidHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + switch (cmdCode) { + case SET_PID_KP: /* Set the P parameter. */ + PID_SetKp(pidHandle, rxData->data[DATA_SEGMENT_THREE].typeF); + ackCode = SetPidAckCode(funcCode); + CUST_AckCode(g_uartTxBuf, (unsigned char)(ackCode + SET_PID_KP), rxData->data[DATA_SEGMENT_THREE].typeF); + break; + case SET_PID_KI: /* Set the I parameter. */ + PID_SetKi(pidHandle, rxData->data[DATA_SEGMENT_THREE].typeF); + ackCode = SetPidAckCode(funcCode); + CUST_AckCode(g_uartTxBuf, (unsigned char)(ackCode + SET_PID_KI), rxData->data[DATA_SEGMENT_THREE].typeF); + break; + case SET_PID_LIMIT: /* Set the pid limit. */ + PID_SetLimit(pidHandle, rxData->data[DATA_SEGMENT_THREE].typeF); + ackCode = SetPidAckCode(funcCode); + CUST_AckCode(g_uartTxBuf, (unsigned char)(ackCode + SET_PID_LIMIT), rxData->data[DATA_SEGMENT_THREE].typeF); + break; + default: + ackCode = 0X77; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + break; + } +} + +/** + * @brief Set motor pid parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetMotorPidParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + + if (funcCode == FOC_CURDAXISPID_PARAMS) { + SetPidParams(&mtrCtrl->currCtrl.dAxisPi, rxData); /* Set Curr loop Daxis pid params */ + } else if (funcCode == FOC_CURQAXISPID_PARAMS) { + SetPidParams(&mtrCtrl->currCtrl.qAxisPi, rxData); /* Set Curr loop Qaxis pid params */ + mtrCtrl->currCtrl.dAxisPi.upperLimit = mtrCtrl->currCtrl.qAxisPi.upperLimit; + mtrCtrl->currCtrl.dAxisPi.lowerLimit = mtrCtrl->currCtrl.qAxisPi.lowerLimit; + } else if (funcCode == FOC_SPDPID_PARAMS) { + SetPidParams(&mtrCtrl->spdCtrl.spdPi, rxData); /* Set Speed loop params */ + } +} + +/** + * @brief Set first order sliding mode observer parameters. + * @param smoHandle The observer control handle. + * @param rxData Receive buffer + */ +static void SetObserverSmo1thParams(FOSMO_Handle *smoHandle, CUSTDATATYPE_DEF *rxData) +{ + smoHandle->kSmo = rxData->data[DATA_SEGMENT_TWO].typeF; + ackCode = 0X09; + CUST_AckCode(g_uartTxBuf, ackCode, smoHandle->kSmo); +} + +/** + * @brief Set first order sliding mode observer's phase-locked loop parameters. + * @param smoHandle The observer control handle. + * @param rxData Receive buffer + */ +static void SetObserverSmo1thPLLParams(FOSMO_Handle *smoHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_SMO1TH_PLL_BDW: /* Set the bandwidth. */ + smoHandle->pll.pllBdw = rxData->data[DATA_SEGMENT_THREE].typeF; + smoHandle->pll.pi.kp = 2.0f * smoHandle->pll.pllBdw; /* kp = 2.0f * pllBdw */ + smoHandle->pll.pi.ki = smoHandle->pll.pllBdw * smoHandle->pll.pllBdw; /* ki = pllBdw * pllBdw */ + ackCode = 0X0A; + CUST_AckCode(g_uartTxBuf, ackCode, smoHandle->pll.pllBdw); + break; + case SET_SMO1TH_SPDFLITER_FC: /* Set the cutoff frequency. */ + smoHandle->spdFilter.fc = rxData->data[DATA_SEGMENT_THREE].typeF; + smoHandle->spdFilter.a1 = 1.0f / (1.0f + DOUBLE_PI * smoHandle->spdFilter.fc * CTRL_CURR_PERIOD); + smoHandle->spdFilter.b1 = 1.0f - smoHandle->spdFilter.a1; + ackCode = 0X0B; + CUST_AckCode(g_uartTxBuf, ackCode, smoHandle->spdFilter.fc); + break; + case SET_SMO1TH_FILCOMPANGLE: /* Set the compensation angle. */ + smoHandle->filCompAngle = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X0C; + CUST_AckCode(g_uartTxBuf, ackCode, smoHandle->filCompAngle); + break; + default: + ackCode = 0X77; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + break; + } +} + +/** + * @brief Set fourth order sliding mode observer parameters. + * @param smo4thHandle The observer control handle. + * @param rxData Receive buffer + */ +static void SetObserverSmo4thParams(SMO4TH_Handle *smo4thHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_SMO4TH_KD: /* Set d axis gain. */ + smo4thHandle->kd = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X0D; + CUST_AckCode(g_uartTxBuf, ackCode, smo4thHandle->kd); + break; + case SET_SMO4TH_KP: /* Set q axis gain. */ + smo4thHandle->kq = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X0E; + CUST_AckCode(g_uartTxBuf, ackCode, smo4thHandle->kq); + break; + default: + break; + } +} + +/** + * @brief Set fourth order sliding mode observer's phase-locked loop parameters. + * @param smo4thHandle The observer control handle. + * @param rxData Receive buffer + */ +static void SetObserverSmo4thPLLParams(SMO4TH_Handle *smo4thHandle, CUSTDATATYPE_DEF *rxData) +{ + smo4thHandle->pll.pllBdw = rxData->data[DATA_SEGMENT_TWO].typeF; + smo4thHandle->pll.pi.kp = (2.0f) * smo4thHandle->pll.pllBdw; /* kp = 2.0f * pllBdw */ + smo4thHandle->pll.pi.ki = smo4thHandle->pll.pllBdw * smo4thHandle->pll.pllBdw; + ackCode = 0X11; + CUST_AckCode(g_uartTxBuf, ackCode, smo4thHandle->pll.pllBdw); +} + +/** + * @brief Set observer parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetObserverParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + + if (funcCode == FOC_OBSERVERTYPE_SMO1TH) { + SetObserverSmo1thParams(&mtrCtrl->smo, rxData); + } else if (funcCode == FOC_OBSERVERTYPE_SMO1TH_PLL) { + SetObserverSmo1thPLLParams(&mtrCtrl->smo, rxData); + } else if (funcCode == FOC_OBSERVERTYPE_SMO4TH) { + SetObserverSmo4thParams(&mtrCtrl->smo4th, rxData); + } else if (funcCode == FOC_OBSERVERTYPE_SMO4TH_PLL) { + SetObserverSmo4thPLLParams(&mtrCtrl->smo4th, rxData); + } +} + +/** + * @brief Set motor speed and speed slope. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetMotorSpdAndSlope(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_SPD_COMMAND_HZ: /* Set target speed(hz). */ + mtrCtrl->spdCmdHz = rxData->data[DATA_SEGMENT_THREE].typeF * mtrCtrl->mtrParam.mtrNp / CONST_VALUE_60; + /* Judgement the value > 0.00001, make sure denominator != 0 */ + if (rxData->data[DATA_SEGMENT_FOUR].typeF > 0.00001f) { + mtrCtrl->spdRmg.delta = mtrCtrl->spdCmdHz / rxData->data[DATA_SEGMENT_FOUR].typeF * CTRL_SYSTICK_PERIOD; + } + ackCode = 0X16; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->spdCmdHz); + break; + case SET_SPD_RMG_SLOPE: /* Set speed slope. */ + mtrCtrl->spdRmg.delta = mtrCtrl->spdCmdHz / rxData->data[DATA_SEGMENT_THREE].typeF * CTRL_SYSTICK_PERIOD; + ackCode = 0X17; + CUST_AckCode(g_uartTxBuf, ackCode, rxData->data[DATA_SEGMENT_THREE].typeF); + break; + default: + break; + } +} + +/** + * @brief Set motor base parameters. + * @param mtrParamHandle The motor parameters handle. + * @param rxData Receive buffer + */ +static void SetMotorBaseParams(MOTOR_Param *mtrParamHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_MAX_ELEC_SPD: /* Set max electric speed. */ + mtrParamHandle->maxElecSpd = rxData->data[DATA_SEGMENT_THREE].typeF / + CONST_VALUE_60 * mtrParamHandle->mtrNp; + ackCode = 0X18; + CUST_AckCode(g_uartTxBuf, ackCode, rxData->data[DATA_SEGMENT_THREE].typeF); + break; + case SET_MOTOR_NUM_OF_PAIRS: /* Set the number of motor pole pairs. */ + mtrParamHandle->mtrNp = (unsigned short)(rxData->data[DATA_SEGMENT_THREE].typeF); + ackCode = 0X19; + CUST_AckCode(g_uartTxBuf, ackCode, (float)mtrParamHandle->mtrNp); + break; + default: + break; + } +} + +/** + * @brief Set motor special parameters. + * @param mtrParamHandle The motor parameters handle. + * @param rxData Receive buffer + */ +static void SetMotorSpecialParams(MOTOR_Param *mtrParamHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_MOTOR_RES_OF_STATOR: /* Set the resistor of stator. */ + mtrParamHandle->mtrRs = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X1A; + CUST_AckCode(g_uartTxBuf, ackCode, mtrParamHandle->mtrRs); + break; + case SET_MOTOR_DAXIS_INDUCTANCE: /* Set the d axis inductance. */ + mtrParamHandle->mtrLd = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X1B; + CUST_AckCode(g_uartTxBuf, ackCode, mtrParamHandle->mtrLd); + break; + case SET_MOTOR_QAXIS_INDUCTANCE: /* Set the q axis inductance. */ + mtrParamHandle->mtrLq = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X1C; + CUST_AckCode(g_uartTxBuf, ackCode, mtrParamHandle->mtrLq); + break; + default: + ackCode = 0X77; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + break; + } +} + +/** + * @brief Set motor board parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void SetMotorBoardParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_SVPWM_VOLTAGE_PER_UNIT: /* Set svpwm voltage per unit. */ + mtrCtrl->sv.voltPu = rxData->data[DATA_SEGMENT_THREE].typeF * ONE_DIV_SQRT3; + mtrCtrl->currCtrl.outLimit = mtrCtrl->sv.voltPu * ONE_DIV_SQRT3; + ackCode = 0X1D; + CUST_AckCode(g_uartTxBuf, ackCode, rxData->data[DATA_SEGMENT_THREE].typeF); + break; + case SET_ADC_CURRENT_SAMPLE_COFE: /* Set adc current sample cofeature. */ + mtrCtrl->adcCurrCofe = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X1E; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->adcCurrCofe); + break; + case SET_CURRENT_LOOP_CONTROL_PERIOD: /* Set current loop control period. */ + mtrCtrl->currCtrlPeriod = 1 / rxData->data[DATA_SEGMENT_THREE].typeF * CONST_VALUE_DIV_1000; + ackCode = 0X1F; + CUST_AckCode(g_uartTxBuf, ackCode, rxData->data[DATA_SEGMENT_THREE].typeF); + break; + default: + break; + } +} + +/** + * @brief Set motor parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetMotorParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + + if (funcCode == MOTOR_PARAMS_BASE) { + SetMotorBaseParams(&mtrCtrl->mtrParam, rxData); + } else if (funcCode == MOTOR_PARAMS_SPECIAL) { + SetMotorSpecialParams(&mtrCtrl->mtrParam, rxData); + } else if (funcCode == MOTOR_PARAMS_BOARD) { + SetMotorBoardParams(mtrCtrl, rxData); + } +} + +/** + * @brief Motor start. + * @param mtrCtrl The motor control handle. + */ +static void CMDCODE_MotorStart(MTRCTRL_Handle *mtrCtrl) +{ + if (mtrCtrl->stateMachine != FSM_RUN) { + SysCmdStartSet(&mtrCtrl->statusReg); /* start motor. */ + mtrCtrl->motorStateFlag = 1; + ackCode = 0X24; /* send ackcode to host. */ + CUST_AckCode(g_uartTxBuf, ackCode, 1); + } +} + +/** + * @brief Motor stop. + * @param mtrCtrl The motor control handle. + */ +static void CMDCODE_MotorStop(MTRCTRL_Handle *mtrCtrl) +{ + SysCmdStopSet(&mtrCtrl->statusReg); + mtrCtrl->motorStateFlag = 0; + ackCode = 0X25; + CUST_AckCode(g_uartTxBuf, ackCode, 0); +} + +/** + * @brief Motor state reset. + * @param mtrCtrl The motor control handle. + */ +static void CMDCODE_MotorReset(MTRCTRL_Handle *mtrCtrl) +{ + BASE_FUNC_UNUSED(mtrCtrl); + BASE_FUNC_SoftReset(); +} + +/** + * @brief Set IF-Startup parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void SetStartupIFParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + + switch (cmdCode) { + case SET_IF_TARGET_CURRENT_VALUE: /* Set I/F start up target current value. */ + mtrCtrl->ifCtrl.targetAmp = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X26; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->ifCtrl.targetAmp); + break; + case SET_INCREMENT_OF_IF_CURRENT: /* Set increment of I/F start up current. */ + mtrCtrl->ifCtrl.stepAmp = mtrCtrl->ifCtrl.targetAmp / rxData->data[DATA_SEGMENT_THREE].typeF * + CTRL_SYSTICK_PERIOD; + ackCode = 0X27; + CUST_AckCode(g_uartTxBuf, ackCode, mtrCtrl->ifCtrl.stepAmp); + break; + case SET_SPEED_RING_BEGIN_SPEED: /* Set speed ring begin speed. */ + mtrCtrl->startup.spdBegin = rxData->data[DATA_SEGMENT_THREE].typeF / + CONST_VALUE_60 * mtrCtrl->mtrParam.mtrNp; + ackCode = 0X28; + CUST_AckCode(g_uartTxBuf, ackCode, rxData->data[DATA_SEGMENT_THREE].typeF); + break; + default: + break; + } +} + +/** + * @brief Set start up parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetStartupParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + + if (funcCode == FOC_STARTUP_IF) { + SetStartupIFParams(mtrCtrl, rxData); + } +} + +/** + * @brief Set adjust speed mode. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_SetAdjustSpdMode(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + /* Get function code. */ + int funcCode = (int)(rxData->data[DATA_SEGMENT_ONE].typeF); + /* Get commond code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + if (funcCode == HOST_SPEED_ADJUST) { + mtrCtrl->spdAdjustMode = HOST_SPEED_ADJUST; + /* Uart connect success. */ + mtrCtrl->uartConnectFlag = CONNECTING; + ackCode = 0X2A; + CUST_AckCode(g_uartTxBuf, ackCode, (float)mtrCtrl->spdAdjustMode); + } else if (funcCode == CUST_SPEED_ADJUST) { + if (cmdCode == 1) { /* If uart connection disconnected & stop motor commond. */ + SysCmdStopSet(&mtrCtrl->statusReg); + mtrCtrl->motorStateFlag = 0; + } + mtrCtrl->spdAdjustMode = CUST_SPEED_ADJUST; + ackCode = 0X2B; + CUST_AckCode(g_uartTxBuf, ackCode, (float)mtrCtrl->spdAdjustMode); + /* Uart disconnect. */ + mtrCtrl->uartConnectFlag = DISCONNECT; + } +} + +/** + * @brief Check uart connect. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + */ +static void CMDCODE_UartHandShake(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData) +{ + CMDCODE_SetAdjustSpdMode(mtrCtrl, rxData); +} + +/** + * @brief Set Motor Initial Status Parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + * @param code Instruction code. + */ +static void CMDCODE_EXE_SetMotorInitParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData, unsigned char code) +{ + switch (code) { + case CMDCODE_SET_OBSERVER_TYPE: { /* Set observer type. */ + CMDCODE_SetObserverType(mtrCtrl, rxData); + } + break; + case CMDCODE_SET_PID_PARAMS: { /* Set motor pid parameters. */ + CMDCODE_SetMotorPidParams(mtrCtrl, rxData); + } + break; + case CMDCODE_SET_OBSERVER_PARAMS: { /* Set observer parameters. */ + CMDCODE_SetObserverParams(mtrCtrl, rxData); + } + break; + case CMDCODE_SET_MOTOR_TARGETSPD: { /* Set motor speed and speed slope. */ + CMDCODE_SetMotorSpdAndSlope(mtrCtrl, rxData); + } + break; + case CMDCODE_SET_MOTOR_PARAMS: { /* Set motor parameters. */ + CMDCODE_SetMotorParams(mtrCtrl, rxData); + } + break; + case CMDCODE_SET_ADJUSTSPD_MODE: /* Set adjust speed mode. */ + CMDCODE_SetAdjustSpdMode(mtrCtrl, rxData); + break; + default: + break; + } +} + +/** + * @brief Set Motor Control System Status. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + * @param code Instruction code. + */ +static void CMDCODE_EXE_SetMotorState(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData, unsigned char code) +{ + BASE_FUNC_UNUSED(rxData); + switch (code) { + case CMDCODE_MOTOR_START: { /* Motor start command */ + CMDCODE_MotorStart(mtrCtrl); + } + break; + case CMDCODE_MOTOR_STOP: { /* Motor stop command */ + CMDCODE_MotorStop(mtrCtrl); + } + break; + case CMDCODE_MOTORSTATE_RESET: { /* Motor reset command */ + CMDCODE_MotorReset(mtrCtrl); + } + break; + default: + break; + } +} + +/** + * @brief Set Startup and Uart Link Handshake Flag Parameters. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + * @param code Instruction code. + */ +static void CMDCODE_EXE_SetOtherParams(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData, unsigned char code) +{ + switch (code) { + case CMDCODE_SET_STARTUP_PARAMS: /* Set start up parameters. */ + CMDCODE_SetStartupParams(mtrCtrl, rxData); + break; + case CMDCODE_UART_HANDSHAKE: { /* Check uart hand shake. */ + CMDCODE_UartHandShake(mtrCtrl, rxData); + } + break; + case CMDCODE_UART_HEARTDETECT: { /* Check uart hand shake. */ + mtrCtrl->uartHeartDetCnt++; + } + break; + default: + break; + } +} +/** + * @brief Instruction code executor. + * @param mtrCtrl The motor control handle. + * @param rxData Receive buffer + * @param code Instruction code. + */ +static void CMDCODE_EXE_Process(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *rxData, unsigned char code) +{ + CMDCODE_EXE_SetMotorInitParams(mtrCtrl, rxData, code); + CMDCODE_EXE_SetMotorState(mtrCtrl, rxData, code); + CMDCODE_EXE_SetOtherParams(mtrCtrl, rxData, code); +} + +/** + * @brief Host data download callback and data parsing. + * @param mtrCtrl The motor control handle. + * @param rxBuf Receive buffer + */ +void CUST_UartDataProcess(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(rxBuf != NULL); + + /* Uart data storage struct */ + CUSTDATATYPE_DEF data; + volatile unsigned char *ptrCnt = &rxBuf[FRAME_CHECK_BEGIN + 1]; + volatile unsigned char *strCnt = &data.data[0].typeCh[0]; + for (unsigned int j = 0; j < FRAME_RECV_DATA_LENTH * FRAME_ONE_DATA_LENTH; j++) { + *strCnt++ = *ptrCnt++; + } + /* Message function code. */ + data.code = rxBuf[FRAME_CHECK_BEGIN]; + CMDCODE_EXE_Process(mtrCtrl, &data, data.code); +} + +/** + * @brief The host computer displays data transmission. + * @param mtrCtrl The motor control handle. + * @param txData Message content. + * @param stage Message status function code. + */ +void CUST_SetTxMsg(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *txData) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(txData != NULL); + if (mtrCtrl->stateMachine == FSM_IDLE) { + mtrCtrl->smo.spdEst = 0.0f; + } + /* Data send to host. */ + txData->data[CURRDQ_Q].typeF = mtrCtrl->idqFbk.q; + txData->data[CURRDQ_D].typeF = mtrCtrl->idqFbk.d; + txData->data[CURRREFDQ_Q].typeF = mtrCtrl->idqRef.q; + txData->data[CURRREFDQ_D].typeF = mtrCtrl->idqRef.d; + /* Motor current speed. */ + txData->data[CURRSPD].typeF = mtrCtrl->smo.spdEst * CONST_VALUE_60 / mtrCtrl->mtrParam.mtrNp; + /* Motor commond speed. */ + txData->data[SPDCMDHZ].typeF = mtrCtrl->spdCmdHz * CONST_VALUE_60 / mtrCtrl->mtrParam.mtrNp; + /* Bus voltage. */ + txData->data[UDC].typeF = mtrCtrl->udc; + /* Power board temprature. */ + txData->data[POWERBOARDTEMP].typeF = mtrCtrl->powerBoardTemp; + /* Motor protection status flag. */ + txData->data[CUST_ERR_CODE].typeI = mtrCtrl->prot.motorErrStatus.all; + /* Three phase current. */ + txData->data[CURRUVW_U].typeF = mtrCtrl->currUvw.u; + txData->data[CURRUVW_V].typeF = mtrCtrl->currUvw.v; + txData->data[CURRUVW_W].typeF = mtrCtrl->currUvw.w; + /* Three phase pwm duty. */ + txData->data[PWMDUTYUVW_U].typeF = mtrCtrl->dutyUvw.u; + txData->data[PWMDUTYUVW_V].typeF = mtrCtrl->dutyUvw.v; + txData->data[PWMDUTYUVW_W].typeF = mtrCtrl->dutyUvw.w; + /* Motor electric angle. */ + txData->data[AXISANGLE].typeF = mtrCtrl->axisAngle; + txData->data[VDQ_Q].typeF = mtrCtrl->vdqRef.q; + txData->data[VDQ_D].typeF = mtrCtrl->vdqRef.d; + txData->data[SPDREFHZ].typeF = mtrCtrl->spdRefHz * CONST_VALUE_60 / mtrCtrl->mtrParam.mtrNp; + txData->data[SENDTIMESTAMP].typeF = mtrCtrl->uartTimeStamp; +} \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.h b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.h new file mode 100644 index 0000000000000000000000000000000000000000..60fe69bb966d5f398468c8093e266796391de4e5 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/cust_process.h @@ -0,0 +1,36 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file cust_process.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of system status. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McsMagicTag_HMI_MOUDLE_H +#define McsMagicTag_HMI_MOUDLE_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "protocol.h" +/* Typedef definitions ------------------------------------------------------------------------- */ + + +void CUST_UartDataProcess(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf); + +void CUST_SetTxMsg(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *txData); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.c b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.c new file mode 100644 index 0000000000000000000000000000000000000000..58bf15a7071e2dbfbea0a799bfd5eebe2d9f8403 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.c @@ -0,0 +1,57 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file hmi_module.c + * @author MCU Algorithm Team + * @brief This file provides functions declaration of human-machine interface. + */ + +#include "hmi_module.h" +#include "mcs_assert.h" + +/** + * @brief HMI Initializatio. + * @retval None. + */ +void HMI_Init(void) +{ + UartRecvInit(); +} + +/** + * @brief HMI processing. + * @param mtrCtrl The motor control handle.. + * @retval None. + */ +void HMI_Process_Rx(MTRCTRL_Handle *mtrCtrl) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + UartModuleProcess_Rx(mtrCtrl); +} + +/** + * @brief HMI processing. + * @param mtrCtrl The motor control handle.. + * @retval None. + */ +void HMI_Process_Tx(MTRCTRL_Handle *mtrCtrl) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + UartModuleProcess_Tx(mtrCtrl); +} diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.h b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.h new file mode 100644 index 0000000000000000000000000000000000000000..056f8d7310eb14335c256933e8d998bf09919cc6 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/hmi_module.h @@ -0,0 +1,37 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file hmi_module.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of system status. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef McsMagicTag_HMI_MOUDLE_H +#define McsMagicTag_HMI_MOUDLE_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "uart_module.h" +/* Typedef definitions ------------------------------------------------------------------------- */ + + +void HMI_Init(void); + +void HMI_Process_Rx(MTRCTRL_Handle *mtrCtrl); +void HMI_Process_Tx(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.c b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.c new file mode 100644 index 0000000000000000000000000000000000000000..f655ada5ea8933139bd474281337ea5360a24fa4 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.c @@ -0,0 +1,174 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file protocol.c + * @author MCU Algorithm Team + * @brief This file provides functions declaration of port communication. + */ + +#include "protocol.h" +#include "apt.h" +#include "typedefs.h" +#include "main.h" +#include "mcs_assert.h" +#include "cust_process.h" + +/** + * @brief Callback function for receiving data analysis and processing. + * @param rxBuf Receive buffer. + */ +__weak void CUST_UartDataProcess(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf) +{ + BASE_FUNC_UNUSED(mtrCtrl); + BASE_FUNC_UNUSED(rxBuf); +} +/** + * @brief User-defined protocol message sending function (weak function). + * @param rxData Sending Messages.. + */ +__weak void CUST_SetTxMsg(MTRCTRL_Handle *mtrCtrl, CUSTDATATYPE_DEF *txData) +{ + BASE_FUNC_UNUSED(mtrCtrl); + BASE_FUNC_UNUSED(*txData); +} + +static void (*g_ptrDataProcess)(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf) = CUST_UartDataProcess; + +/** + * @brief Frame checksum. + * @param ptr Pointer to the data to be checked + * @param num Number of bytes + * @retval unsigned char Checksum + */ +static unsigned char CheckSum(unsigned char *ptr, unsigned char num) +{ + unsigned char sum = 0; + unsigned char *p = ptr; + /* Calculate the sum of received data. */ + for (unsigned char i = 0; i < num; i++) { + sum += (unsigned char)*p; + p++; + } + return sum; +} + +/** + * @brief Transmitting Data Frames. + * @param mtrCtrl The motor control handle. + * @param txBuf Sending Messages. + */ +unsigned int CUST_TransmitData(MTRCTRL_Handle *mtrCtrl, unsigned char *txBuf) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(txBuf != NULL); + unsigned int dataLen = FRAME_ONE_DATA_LENTH * SEND_FRAME_DATA_NUM; + unsigned char i = 0; + CUSTDATATYPE_DEF txData = {0}; + CUST_SetTxMsg(mtrCtrl, &txData); + txBuf[i++] = FRAME_START; + /* Message function code */ + txBuf[i++] = FRAME_SENT; + /* Message data */ + for (unsigned char x = 0; x < SEND_FRAME_DATA_NUM; x++) { + unsigned char floatIndex = 0; + unsigned char byteOffset = i; + txBuf[x * FRAME_ONE_DATA_LENTH + byteOffset++] = txData.data[x].typeCh[floatIndex++]; + txBuf[x * FRAME_ONE_DATA_LENTH + byteOffset++] = txData.data[x].typeCh[floatIndex++]; + txBuf[x * FRAME_ONE_DATA_LENTH + byteOffset++] = txData.data[x].typeCh[floatIndex++]; + txBuf[x * FRAME_ONE_DATA_LENTH + byteOffset++] = txData.data[x].typeCh[floatIndex++]; + } + /* Message verification domain */ + txBuf[dataLen + i++] = CheckSum((unsigned char*)&txBuf[FRAME_CHECK_BEGIN], dataLen + 1); + /* End of Message */ + txBuf[dataLen + i++] = FRAME_END; + return dataLen + i; +} + +/** + * @brief Transmitting Data Frames. + * @param txBuf Sending Cust Ack Code. + * @param ackCode Ack Code. + * @param varParams Host set parameter. + */ +void CUST_AckCode(unsigned char *txBuf, unsigned char ackCode, float varParams) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(txBuf != NULL); + CUSTDATATYPE_DEF txData = {0}; + int dataIndex = 0; + unsigned int i = 0; + unsigned int txLen = 0; + unsigned char dataLen = FRAME_ONE_CHAR_LENTH + FRAME_ONE_DATA_LENTH; + + txData.data[0].typeF = varParams; + txBuf[i++] = FRAME_START; + /* Message function code */ + txBuf[i++] = FRAME_CUSTACK; + /* Message ack code */ + txBuf[i++] = ackCode; + /* Message data */ + txBuf[i++] = txData.data[0].typeCh[dataIndex++]; + txBuf[i++] = txData.data[0].typeCh[dataIndex++]; + txBuf[i++] = txData.data[0].typeCh[dataIndex++]; + txBuf[i++] = txData.data[0].typeCh[dataIndex++]; + + /* Message verification domain */ + txBuf[FRAME_ONE_CHAR_LENTH + i++] = CheckSum((unsigned char*)&txBuf[FRAME_CHECK_BEGIN], dataLen + 1); + /* End of Message */ + txBuf[FRAME_ONE_CHAR_LENTH + i++] = FRAME_END; + txLen = FRAME_ONE_CHAR_LENTH + i++; + HAL_UART_WriteIT(&g_uart0, txBuf, txLen); +} + +/** + * @brief Cust receive data process. + * @param mtrCtrl The motor control handle. + * @param rxBuf Receive buffer + */ +void CUST_DataReceProcss(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(rxBuf != NULL); + unsigned char g_uartTxBuf[10] = {0}; + unsigned char ackCode = 0; + /* Frame header check */ + if (rxBuf[0] != FRAME_START) { + ackCode = 0X78; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + return; + } + /* Frame trailer check */ + if (rxBuf[FRAME_LENTH - 1] != FRAME_END) { + ackCode = 0X79; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + return; + } + /* Checksum */ + if (CheckSum((unsigned char*)&rxBuf[FRAME_CHECK_BEGIN], FRAME_CHECK_NUM) != rxBuf[FRAME_CHECKSUM]) { + ackCode = 0X7A; + CUST_AckCode(g_uartTxBuf, ackCode, 0); + return; + } else { + if (g_ptrDataProcess == NULL) { + return; + } else { + g_ptrDataProcess(mtrCtrl, rxBuf); + } + } +} diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.h b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..900a00d8065b0154f3883d213be12f63610d0be1 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/protocol.h @@ -0,0 +1,121 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file protocol.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of port communication. + */ +#ifndef McsMagicTag_PORTOCOL_H +#define McsMagicTag_PORTOCOL_H + +#include "uart.h" +#include "mcs_carrier.h" + +#define RS485_SEND_ENABLE GPIO6->GPIO_DATA[GPIO_PIN_7].reg = GPIO_PIN_7 +#define RS485_SEND_DISABLE GPIO6->GPIO_DATA[GPIO_PIN_7].reg = BASE_CFG_UNSET + +#define RX_BUF_LEN (16) +#define SEND_FRAME_DATA_NUM (CUSTDATA_MAX) +/* Service Uart0 Communication Deal */ +#define FRAME_ONE_DATA_LENTH 4 +#define FRAME_ONE_CHAR_LENTH 1 +#define FRAME_RECV_DATA_LENTH 4 +#define FRAME_LENTH 20 /* Data length */ +#define FRAME_SENT 0X8F +#define FRAME_CUSTACK 0X8A +#define FRAME_START 0x0F /* Start frame */ +#define FRAME_END '/' /* StOP frame */ +#define FRAME_CHECK_BEGIN 1 /* Check frame */ +#define FRAME_CHECKSUM 18 /* Check sum */ +#define FRAME_CHECK_NUM 17 +#define CMDCODE_IDLE_FRAME 0x55 /* Fill frame */ +#define CMDCODE_GET_MOTOR_PARAMS 0x01 +#define CMDCODE_SEND_MOTOR_PARAMS 0x02 +#define CMDCODE_SET_MOTOR_CTLMODE 0x03 +#define CMDCODE_SET_OBSERVER_TYPE 0x04 +#define CMDCODE_SET_STARTUP_MODE 0x05 +#define CMDCODE_SET_PID_PARAMS 0x06 +#define CMDCODE_SET_STARTUP_PARAMS 0x07 +#define CMDCODE_SET_OBSERVER_PARAMS 0x08 +#define CMDCODE_SET_MOTOR_TARGETSPD 0x09 +#define CMDCODE_SET_MOTOR_PARAMS 0x0A +#define CMDCODE_MOTOR_START 0x0B +#define CMDCODE_MOTOR_STOP 0x0C +#define CMDCODE_MOTORSTATE_RESET 0x0D +#define CMDCODE_SEND_FIRMVERSION 0x0E +#define CMDCODE_SET_ADJUSTSPD_MODE 0x11 +#define CMDCODE_UART_HANDSHAKE 0x12 +#define CMDCODE_UART_HEARTDETECT 0x13 + +typedef union { + unsigned char typeCh[4]; + float typeF; + int typeI; +} UNIONDATATYPE_DEF; + +typedef enum { + OFFLINE_RES = 0, + OFFLINE_LD, + OFFLINE_LQ, + OFFLINE_PSIF, + OFFLINE_JS, + OFFLINE_NP, + OFFLINE_B, + OFFLINE_KPD, + OFFLINE_KID, + OFFLINE_KPQ, + OFFLINE_KIQ, + OFFLINE_KPS, + OFFLINE_KIS, + OFFLINE_SPEED, + OFLINE_MAX +} OFFLINE_IDEN_TYPE; + +typedef enum { + CURRDQ_Q = 0, + CURRDQ_D, + CURRREFDQ_Q, + CURRREFDQ_D, + CURRSPD, + SPDCMDHZ, + UDC, + POWERBOARDTEMP, + CUST_ERR_CODE, + CURRUVW_U, + CURRUVW_V, + CURRUVW_W, + PWMDUTYUVW_U, + PWMDUTYUVW_V, + PWMDUTYUVW_W, + AXISANGLE, + VDQ_Q, + VDQ_D, + SPDREFHZ, + SENDTIMESTAMP, + CUSTDATA_MAX +} SENDTOHOSTPARAMS; + +typedef struct { + volatile unsigned char code; + volatile UNIONDATATYPE_DEF data[SEND_FRAME_DATA_NUM]; +} CUSTDATATYPE_DEF; + + +void CUST_DataReceProcss(MTRCTRL_Handle *mtrCtrl, unsigned char *rxBuf); +unsigned int CUST_TransmitData(MTRCTRL_Handle *mtrCtrl, unsigned char *txBuf); +void CUST_AckCode(unsigned char *txBuf, unsigned char ackCode, float varParams); +#endif /* McsMagicTag_PORTOCOL_H */ diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.c b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.c new file mode 100644 index 0000000000000000000000000000000000000000..6b231c02a247ba3ffc0c25cb9f5f680b2b3b92dd --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.c @@ -0,0 +1,198 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file uart_module.c + * @author MCU Algorithm Team + * @brief This file provides functions declaration of Serial port communication. + */ +#include "uart_module.h" +#include "debug.h" +#include "main.h" +#include "baseinc.h" + +/* Buffer size */ +#define UI_TX_BUF_LEN (96) +#define UI_RX_BUF_LEN (96) + +/* Receiving Timeout Interval */ +#define UART_TIME_OUT_MS (100) + +/* Start sending data to host delay after uart connect success */ +#define UART_UPDATA_DELAY_TIME_MS (50) + +/* Uart baudrate */ +#define UART0BAUDRATE (1843200) + +/* Data buffer */ +unsigned char g_uartRxBuf[UI_RX_BUF_LEN] = {0}; +unsigned char g_uartTxBuf[UI_TX_BUF_LEN] = {0}; +static unsigned int getdeltaSystickCnt = 0; +static FRAME_Handle g_uartFrame; +/** + * @brief Receive Data Clear. + * @param uartFrame Receice Data. + */ +static void FrameRecvClear(FRAME_Handle *uartFrame) +{ + /* Clear buffer lenth. */ + uartFrame->buffLen = 0; + uartFrame->timeOutCnt = 0; + uartFrame->frameFlag = 0; + /* Clear received data lenth. */ + uartFrame->rxLen = 0; + /* Clear received flag. */ + uartFrame->rxFlag = 0; + uartFrame->upDataCnt = 0; +} + +/** + * @brief Set Dma status. + * @param mtrCtrl The motor control handle. + */ +static void SetUartDmaStatus(MTRCTRL_Handle *mtrCtrl) +{ + /* Delay 50ms start uart Tx DMA . */ + if (mtrCtrl->uartConnectFlag == CONNECTING && g_uartFrame.upDataDelayCnt++ > UART_UPDATA_DELAY_TIME_MS) { + g_uartFrame.txFlag = 1; /* Start send data flag. */ + mtrCtrl->uartConnectFlag = CONNECTED; + g_uartFrame.upDataDelayCnt = 0; + } + if (mtrCtrl->uartConnectFlag == DISCONNECT) { + g_uartFrame.txFlag = 0; /* Stop send data flag. */ + mtrCtrl->uartTimeStamp = 0; + } +} + +/** + * @brief Set uart baudRate. + * @param baudrate Uart baudRate. + */ +static void SetUartBaudRate(unsigned int baudrate) +{ + /* Re_Write uart0 baudrate. */ + g_uart0.baudRate = baudrate; + HAL_UART_Init(&g_uart0); +} + +/** + * @brief Uart Dma interupt callback func. + * @param null. + */ +void UART0_TXDMACallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + unsigned int getCurSystickCnt = 0; + static unsigned int getlastSystickCnt = 0; + /* USER CODE BEGIN UART0_WRITE_DMA_FINISH */ + g_uartFrame.txFlag = 1; + getCurSystickCnt = DCL_SYSTICK_GetTick(); + if (getlastSystickCnt != 0) { + /* Calculate unit frame data send time */ + getdeltaSystickCnt = getCurSystickCnt - getlastSystickCnt; + } + getlastSystickCnt = getCurSystickCnt; + /* USER CODE END UART0_WRITE_DMA_FINISH */ +} + +/** + * @brief Uart0 interruput Write CallBack Function. + * @param handle Uart handle. + */ +void UART0WriteInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_WRITE_IT_FINISH */ + g_uartFrame.uartItTxFlag = 1; + g_uartFrame.txFlag = 1; + /* USER CODE END UART0_WRITE_IT_FINISH */ +} + +/** + * @brief Uart0 Interruput Read CallBack Function. + * @param handle Uart handle. + */ +void UART0ReadInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_READ_IT_FINISH */ + if (g_uartFrame.rxLen >= UI_RX_BUF_LEN - 1) { + g_uartFrame.rxLen = 0; + } + HAL_UART_ReadIT(handle, &g_uartFrame.rxData, 1); + g_uartRxBuf[g_uartFrame.rxLen] = g_uartFrame.rxData; + g_uartFrame.rxLen++; + g_uartFrame.rxFlag = 1; + g_uartFrame.uartItTxFlag = 0; + return; + /* USER CODE END UART0_READ_IT_FINISH */ +} + +/** + * @brief Uart Read Data Init Function. + * @param void. + */ +void UartRecvInit(void) +{ + /* Uart reception initialization */ + FrameRecvClear(&g_uartFrame); + SetUartBaudRate(UART0BAUDRATE); + HAL_UART_ReadIT(&g_uart0, &g_uartFrame.rxData, 1); +} + +/** + * @brief Uart Read Data Process Function. + * @param mtrCtrl The motor control handle. + */ +void UartModuleProcess_Rx(MTRCTRL_Handle *mtrCtrl) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + SetUartDmaStatus(mtrCtrl); + if (g_uartFrame.rxFlag == 1) { /* Receive data flag. */ + if (g_uartFrame.timeOutCnt++ > UART_TIME_OUT_MS) { + /* Received data from the host. */ + g_uartFrame.frameFlag = 1; + g_uartFrame.rxFlag = 0; + g_uartFrame.timeOutCnt = 0; + /* Execute data process. */ + CUST_DataReceProcss(mtrCtrl, g_uartRxBuf); + g_uartFrame.rxLen = 0; + } + } + g_uartFrame.frameFlag = 0; +} + +/** + * @brief Uart Write Data Process Function. + * @param mtrCtrl The motor control handle. + */ +void UartModuleProcess_Tx(MTRCTRL_Handle *mtrCtrl) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + if (g_uartFrame.txFlag == 1) { /* Send data flag. */ + mtrCtrl->uartTimeStamp = (float)getdeltaSystickCnt; /* Unit data time stamp */ + g_uartFrame.upDataCnt = 0; + g_uartFrame.txFlag = 0; + /* Send data to host. */ + unsigned int txLen = CUST_TransmitData(mtrCtrl, g_uartTxBuf); + /* If txIT mode send data finish, convert to DMA mode */ + if (g_uartFrame.uartItTxFlag == 1) { + HAL_UART_WriteDMA(&g_uart0, g_uartTxBuf, txLen); + } + } +} diff --git a/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.h b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.h new file mode 100644 index 0000000000000000000000000000000000000000..1b3588ea132e4bafdfa4e831b9e4e8b0ad4efdd2 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/lunyi/user_interface/uart_module.h @@ -0,0 +1,46 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file uart_module.h + * @author MCU Algorithm Team + * @brief This file provides functions declaration of Serial port communication. + */ +#ifndef McsMagicTag_UART_MODULE_H +#define McsMagicTag_UART_MODULE_H + +#include "protocol.h" +#include "mcs_ctlmode_config.h" + +typedef struct { + unsigned int buffLen; + unsigned int timeOutCnt; + unsigned char frameFlag; + unsigned int rxLen; + unsigned char rxFlag; + unsigned char txFlag; + unsigned char rxData; + unsigned int upDataCnt; + unsigned int upDataDelayCnt; + unsigned char uartItTxFlag; +} FRAME_Handle; + + +void UartRecvInit(void); +void UartModuleProcess_Rx(MTRCTRL_Handle *mtrCtrl); +void UartModuleProcess_Tx(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/others/demo/zhinenglunyi/main.c b/vendor/others/demo/zhinenglunyi/main.c new file mode 100644 index 0000000000000000000000000000000000000000..a9029a3092ae14a0189a617d707f636b5055e2d9 --- /dev/null +++ b/vendor/others/demo/zhinenglunyi/main.c @@ -0,0 +1,72 @@ +/** + * @copyright Copyright (c) 2022, HiSilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * @file main.c + * @author MCU Driver Team + * @brief Main program body. + */ + +#include "typedefs.h" +#include "feature.h" +#include "mcs_motor_process.h" +#include "main.h" +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +ACMP_Handle g_acmp0; +PGA_Handle g_pga0; +PGA_Handle g_pga1; +TIMER_Handle g_timer0; +TIMER_Handle g_timer1; +UART_Handle g_uart0; +APT_Handle g_apt0; +APT_Handle g_apt1; +APT_Handle g_apt2; +ADC_Handle g_adc0; +DMA_Handle g_dmac; +GPIO_Handle g_gpio2; +GPIO_Handle g_gpio1; +GPIO_Handle g_gpio4; +GPIO_Handle g_gpio5; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ +/* USER CODE END 1 */ + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + /* USER CODE END 2 */ + MotorMainProcess(); + /* USER CODE BEGIN 3 */ + /* 建议用户放置初始配置代码 */ + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + /* 建议用户放置周期性执行代码 */ + /* USER CODE END 4 */ + } + /* USER CODE BEGIN 5 */ + /* 建议用户放置代码流程 */ + /* USER CODE END 5 */ + return BASE_STATUS_OK; +} + +/* USER CODE BEGIN 6 */ +/* 建议用户放置自定义函数 */ +/* USER CODE END 6 */ \ No newline at end of file