diff --git a/src/application/board_sample/sample_dimming/feature.h b/src/application/board_sample/sample_dimming/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..38a0a3d5c361856761b021d2724e12c4c6777f3c --- /dev/null +++ b/src/application/board_sample/sample_dimming/feature.h @@ -0,0 +1,120 @@ +/** + * @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. + * @date 2025-04-09 18:35:27 + */ + +#ifndef McuMagicTag_FEATURE_H +#define McuMagicTag_FEATURE_H + +/* Macro definitions --------------------------------------------------------- */ +#define MACRO_ENABLE 1 +#define MACRO_DISABLE 0 + +#define CHIP_3066MNPIRH MACRO_ENABLE + +/* 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. */ + +#define MCS_PARAM_CHECK MACRO_ENABLE +#define APT_PARAM_CHECK MACRO_ENABLE +#define ADC_PARAM_CHECK MACRO_ENABLE +#define CAPM_PARAM_CHECK MACRO_ENABLE +#define CRG_PARAM_CHECK MACRO_ENABLE +#define I2C_PARAM_CHECK MACRO_ENABLE +#define UART_PARAM_CHECK MACRO_ENABLE +#define SPI_PARAM_CHECK MACRO_ENABLE +#define TIMER_PARAM_CHECK MACRO_ENABLE +#define IWDG_PARAM_CHECK MACRO_ENABLE +#define WWDG_PARAM_CHECK MACRO_ENABLE +#define GPIO_PARAM_CHECK MACRO_ENABLE +#define GPT_PARAM_CHECK MACRO_ENABLE +#define DMA_PARAM_CHECK MACRO_ENABLE +#define CRC_PARAM_CHECK MACRO_ENABLE +#define CFD_PARAM_CHECK MACRO_ENABLE +#define CMM_PARAM_CHECK MACRO_ENABLE +#define CAN_PARAM_CHECK MACRO_ENABLE +#define FLASH_PARAM_CHECK MACRO_ENABLE +#define PMC_PARAM_CHECK MACRO_ENABLE +#define ACMP_PARAM_CHECK MACRO_ENABLE +#define DAC_PARAM_CHECK MACRO_ENABLE +#define PGA_PARAM_CHECK MACRO_ENABLE +#define IOCMG_PARAM_CHECK MACRO_ENABLE +#define QDM_PARAM_CHECK MACRO_ENABLE + +/* 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 25000000U + +#define DBG_USE_NO_PRINTF 0U +#define DBG_USE_UART_PRINTF 1U + +#define DBG_PRINTF_USE DBG_USE_NO_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/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \344\272\247\345\223\201\347\256\200\344\273\213 V01.pdf" "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \344\272\247\345\223\201\347\256\200\344\273\213 V01.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..7d0119000441d0118177240151d976cd6fd5d0af Binary files /dev/null and "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \344\272\247\345\223\201\347\256\200\344\273\213 V01.pdf" differ diff --git "a/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \346\225\260\346\215\256\346\211\213\345\206\214 V01.pdf" "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \346\225\260\346\215\256\346\211\213\345\206\214 V01.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..2dcee0bef1638c115c13e18e75ec2e432a34a1fb Binary files /dev/null and "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227 \346\225\260\346\215\256\346\211\213\345\206\214 V01.pdf" differ diff --git "a/src/document/datasheet/3061M/3061M\347\263\273\345\210\227\346\212\200\346\234\257\345\217\202\350\200\203\346\214\207\345\215\227 V02.pdf" "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227\346\212\200\346\234\257\345\217\202\350\200\203\346\214\207\345\215\227 V02.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..ec73036f0fb16e4ddea550377ecebee55f96f294 Binary files /dev/null and "b/src/document/datasheet/3061M/3061M\347\263\273\345\210\227\346\212\200\346\234\257\345\217\202\350\200\203\346\214\207\345\215\227 V02.pdf" differ diff --git a/vendor/yibaina_3061M/AS5600_IIC/readme.md b/vendor/yibaina_3061M/AS5600_IIC/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..816a24d1a88ce453cabe152c562f0c9ea4839591 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/readme.md @@ -0,0 +1,29 @@ +# AS5600_IIC + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的AS5600磁编码器的应用 + +**【环境要求】** + +- 编码器选用AS5600 + +- 编码器安装上电机,磁铁与编码器表面距离为0.5-3mm之间 + +- 接线方式: + + ic0_SCL---GPIO4_5---J2_21 + + ic0_SDA---GPIO4_3---J2_26 + + 5v ---J1_17 + + GND---J1_7 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 编码器固定后,转动电机可以获取电机位置值 diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/feature.h b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..715371be1e997b17c000b9d77eebcb18d838968e --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/feature.h @@ -0,0 +1,94 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#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/yibaina_3061M/AS5600_IIC/user/generatecode/main.h b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..40d65b1d6f31f1445aac968ab0626aeab2c4e93f --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/main.h @@ -0,0 +1,98 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +/* 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; + +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); + +/* 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/yibaina_3061M/AS5600_IIC/user/generatecode/system_init.c b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..d49cd86016784553de8e7a45998524d3e24e3b24 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/generatecode/system_init.c @@ -0,0 +1,677 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_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); +} + +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); + + 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_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* 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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER0) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 1000000; + + g_timer0.baseAddress = TIMER0; + g_timer0.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer0.bgLoad = (load < 1) ? 0 : (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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer1.bgLoad = (load < 1) ? 0 : (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_BAUD_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 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/yibaina_3061M/AS5600_IIC/user/main.c b/vendor/yibaina_3061M/AS5600_IIC/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..d6ab767c3f2ad43dd09113ef5b0ca28d40a698ce --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/main.c @@ -0,0 +1,71 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#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; +/* 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 diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..dea3ad66fde865889d8480d222b97f3900bd7dac --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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; /**< Motor start/stop status flag. */ + 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; /**< Current sampling mode setting: single resistor, double resistor. */ + 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; /**< Dual-resistance/three-resistance sampling SVPWM Handle. */ + R1SVPWM_Handle r1Sv; /**< Single-resistance phase-shifted SVPWM handle. */ + 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; /**< Motor protect status detection flag bit handle. */ +} MTRCTRL_Handle; + +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h new file mode 100644 index 0000000000000000000000000000000000000000..38c00b5ddbf9f63ab1a2e5b644eea55d634727ad --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h @@ -0,0 +1,76 @@ +/** + * @ 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" + +#if defined (CHIP_3061MNPICA) || defined (CHIP_3061MNPIKA) || defined (CHIP_3061MNNICA) || \ + defined (CHIP_3061MNNIKA) || defined (CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) || \ + defined (CHIP_3061MNPIK8) || defined (CHIP_3061MNNIK8) + + #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) || defined (CHIP_3066MNPIRH) || \ + defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) + + #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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6f38cccf3fb92d52b4874390805a520e255b2f --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/demo/sample_gpio_key/gpio_key_sample.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h similarity index 76% rename from vendor/yibaina_3061M/demo/sample_gpio_key/gpio_key_sample.h rename to vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h index 17ff5146931f2a3e009ca4ae8363316a4d240653..783bf21402d5d3f5d4bdc8dc5bd9ee425d0fbf21 100644 --- a/vendor/yibaina_3061M/demo/sample_gpio_key/gpio_key_sample.h +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h @@ -1,30 +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 gpio_key_sample.h - * @author MCU Driver Team - * @brief GPIO module sample - * @details This file provides sample code for users to help use - * the trigger an interrupt based on the key connected to the GPIO. - */ - -#ifndef GPIO_KEY_SAMPLE_H -#define GPIO_KEY_SAMPLE_H - -BASE_StatusType GPIO_KeySample(void); - -#endif /* GPIO_KEY_SAMPLE_H */ \ No newline at end of file +/** + * @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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..19510c78b2d63a46ca51495d8ad028e351574d1d --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..d912206cb074fc57bf8450adcddcd72be2125e02 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h @@ -0,0 +1,108 @@ +/** + * @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 /* Capacitor charging time. */ + +#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. */ + +#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 /* SMO4TH PLL Bandwidth. */ +#define SMO4TH_KD 300.0f /* SMO4TH parameters KD. */ +#define SMO4TH_KQ 600.0f /* SMO4TH parameters KQ. */ +#define SMO4TH_SPD_FILTER_CUTOFF_FREQ 40.0f /* SMO4TH speed cutoff frequency of speed filter. */ + +/* User_Commond */ +#define CTRL_IF_CURR_AMP_A 0.3f /* IF control current amplitude. */ +#define USER_TARGET_SPD_HZ 100.0f /* User-defined target speed value. */ +#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 /* User-defined maximum speed value. */ +#define USER_MIN_SPD_HZ 35.0f /* User-defined minimum speed value. */ +#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 /* Current loop Q axis Kp. */ +#define CURRQAXIS_KI 20612.84f /* Current loop Q axis Ki. */ +#define CURRDAXIS_KP 3.477114f /* Current loop D axis Kp. */ +#define CURRDAXIS_KI 20612.84f /* Current loop D axis Ki. */ +/* Current loop PID output lower limit. */ +#define CURR_LOWERLIM (-INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) +/* Current loop PID output upper limit. */ +#define CURR_UPPERLIM (INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) + +#define SPD_KP 0.00505f /* Speed loop Kp. */ +#define SPD_KI 0.012f /* Speed loop Ki. */ +#define SPD_LOWERLIM (-0.105f) /* Speed loop PID output lower limit. */ +#define SPD_UPPERLIM 0.105f /* Speed loop PID output upper limit. */ + +/* 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 = 14, \ + .mtrRs = 10.1f, \ + .mtrLd = 0.010f, \ + .mtrLq = 0.010f, \ + .mtrPsif = 0.0f, \ + .mtrJ = 0.0f, \ + .maxElecSpd = 180.25f, \ + .maxCurr = 1.0f, \ + .busVolt = INV_VOLTAGE_BUS, \ +} + +/* Bus voltage sampling conversion factor. */ +#define ADC_UDC_COFFI 0.01289f /* 0.01289 = 3.3/4096*192/12. */ + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c new file mode 100644 index 0000000000000000000000000000000000000000..99766bdf9b3d4f161b1902708696cb0e75a4fc9c --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h new file mode 100644 index 0000000000000000000000000000000000000000..104a5decba9eeb22375b63e4def4278af37d3573 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c new file mode 100644 index 0000000000000000000000000000000000000000..e97876b7c6ec522fa82c30cbe503e2ab8de288db --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h new file mode 100644 index 0000000000000000000000000000000000000000..365110e10c6cd8bd5207af61f0a87b6df226fa91 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..0e27318ce3a47c429526b39672b3e4e0d9762111 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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 (1.0f) +/**< 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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..da4e56f89a51d39053fad4511bb799c91070df65 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..e9916fe491699bff3373bbc68b175b6db16d7cd7 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..b0541a2e2e37ba98e8b92e6334ab2cc940b72b6c --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..0435156a0add386ec4b783f4d003f4178baa2ecf --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee4d2d240e66f7cfb0528b2d42d4c32ada0078 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d1e4bed11bec0d6d73aee54de36c365588898e --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..184ba4a3ac712690e4f808f1464a65c74a387b52 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9d99a76c19f53a78ccc1257287eccfd1fc972c --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/readme.md b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..98b2a068ddfaef196002273aaedc90123a0cd0de --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/readme.md @@ -0,0 +1,10 @@ +# pmsm_sensorless_2shunt_foc + +**【功能描述】** ++ 基于ECMCU105H/ECBMCU201MPC单板的单电机双电阻采样Foc应用 + +**【环境要求】** ++ 所有单板电源改制为演示用的12V低压,电机选用Gimbal GBM2804H-100T + +**【IDE配置方法】** ++ chipConfig中的Sample栏目里面选中pmsm sensorless 2shunt foc示例,然后点击生成代码即可 diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..9fc8afac32ecb5810db6758fb6acbca42a4c0f69 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..79bc3949d31044e401311212f30ff7c6ef3d136f --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c @@ -0,0 +1,950 @@ +/** + * @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}; + +/* 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.adc0Compensate = ADC0COMPENSATE; /* Phase-u current init adc shift trim value */ + g_mc.adc1Compensate = ADC1COMPENSATE; /* Phase-w current init adc shift trim value */ + + 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); + if (g_mc.sampleMode == DUAL_RESISTORS) { + SVPWM_Init(&g_mc.sv, INV_VOLTAGE_BUS * ONE_DIV_SQRT3); /* Dual resistors SVPWM init. */ + } else if (g_mc.sampleMode == SINGLE_RESISTOR) { + /* Single resistor SVPWM init. */ + 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. + * @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. + * @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. + * @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; + } + } + if (adcSampleTimes < 1.0f) { + adcSampleTimes = 1.0f; /* Prevent divide-by-zero errors */ + } + 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. + * @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. + * @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. + * @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 = 0.0f; + /* 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); + static float potentiomitorAdcValue = 0.0f; + static float spdCmdHz = 0; + static float spdCmdHzLast = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHzLast init value */ + HAL_ADC_SoftTrigSample(&ADCPTT_HANDLE, ADCPTTSOCNUM); + BASE_FUNC_DELAY_US(10); /* Delay 10 us. */ + potentiomitorAdcValue = (float)HAL_ADC_GetConvResult(&ADCPTT_HANDLE, ADCPTTSOCNUM); + /* 4045.0 is adc sample max value of potentiomitor, convert max spd to 180.25Hz */ + spdCmdHz = potentiomitorAdcValue / 4045.0f * USER_MAX_SPD_HZ; + if (Abs(spdCmdHzLast - spdCmdHz) < 1.0f) { /* Ignore changes less than 1. */ + return; + } + spdCmdHzLast = spdCmdHz; + if (spdCmdHz < USER_MIN_SPD_HZ) { /* 35.0 is spdCmdHz lower limit */ + spdCmdHz = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHz lower limit */ + } + if (spdCmdHz > g_mc.mtrParam.maxElecSpd) { /* spdCmdHz upper limit */ + spdCmdHz = g_mc.mtrParam.maxElecSpd; /* spdCmdHz upper limit */ + } + if (g_mc.spdAdjustMode == CUST_SPEED_ADJUST) { + g_mc.spdCmdHz = spdCmdHz; + } +} + +/** + * @brief System timer ISR for Motor Statemachine CallBack function. + * @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. */ + 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 */ + g_mc.readCurrUvwCb = ReadCurrUvw; + g_mc.setPwmDutyCb = SetPwmDutyCp; + g_mc.setADCTriggerTimeCb = SetADCTriggerTime; +} + +/** + * @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); + } + } +} + +/** + * @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); + + /* Disable PWM output before startup. */ + 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); + while (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 */ + 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; + } + } + return 0; +} diff --git a/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c new file mode 100644 index 0000000000000000000000000000000000000000..7c4f75252f9cb7a7fd3b2452ad276e8074519121 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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); + float pllBdw = 0.0f; + switch (cmdCode) { + case SET_SMO1TH_PLL_BDW: /* Set the bandwidth. */ + pllBdw = rxData->data[DATA_SEGMENT_THREE].typeF; + smoHandle->pll.pi.kp = 2.0f * pllBdw; /* kp = 2.0f * pllBdw */ + smoHandle->pll.pi.ki = pllBdw * pllBdw; /* ki = pllBdw * pllBdw */ + ackCode = 0X0A; + CUST_AckCode(g_uartTxBuf, ackCode, 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) +{ + float pllBdw = rxData->data[DATA_SEGMENT_TWO].typeF; + smo4thHandle->pll.pi.kp = (2.0f) * pllBdw; /* kp = 2.0f * pllBdw */ + smo4thHandle->pll.pi.ki = pllBdw * pllBdw; + ackCode = 0X11; + CUST_AckCode(g_uartTxBuf, ackCode, 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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h new file mode 100644 index 0000000000000000000000000000000000000000..60fe69bb966d5f398468c8093e266796391de4e5 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c new file mode 100644 index 0000000000000000000000000000000000000000..58bf15a7071e2dbfbea0a799bfd5eebe2d9f8403 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h new file mode 100644 index 0000000000000000000000000000000000000000..056f8d7310eb14335c256933e8d998bf09919cc6 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c new file mode 100644 index 0000000000000000000000000000000000000000..56f0c0bb3fa394c355dcbef7f6387270bf31dd67 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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_WriteDMA(&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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..900a00d8065b0154f3883d213be12f63610d0be1 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c new file mode 100644 index 0000000000000000000000000000000000000000..df5e918648921817e0e0fd5c9d98c5c0ee6bcb26 --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c @@ -0,0 +1,184 @@ +/** + * @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) + +/* 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. + * @retval None. + */ +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; + uartFrame->rxAckFlag = 0; +} + +/** + * @brief Set Dma status. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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 Uart Dma interupt callback func. + * @param handle Uart handle. + * @retval None. + */ +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; + /* Received information answered, information update reserved. */ + if (g_uartFrame.rxAckFlag == 1) { + g_uartFrame.uartItTxFlag = 1; + g_uartFrame.rxAckFlag = 0; + } + 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 Read CallBack Function. + * @param handle Uart handle. + * @retval None. + */ +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. + * @retval None. + */ +void UartRecvInit(void) +{ + /* Uart reception initialization */ + FrameRecvClear(&g_uartFrame); + HAL_UART_ReadIT(&g_uart0, &g_uartFrame.rxData, 1); +} + +/** + * @brief Uart Read Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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.rxAckFlag = 1; + g_uartFrame.rxLen = 0; + } + } + g_uartFrame.frameFlag = 0; +} + +/** + * @brief Uart Write Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h new file mode 100644 index 0000000000000000000000000000000000000000..f1f8f89951fd2ab017f9ad6082a2542ca925aaaa --- /dev/null +++ b/vendor/yibaina_3061M/AS5600_IIC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h @@ -0,0 +1,47 @@ +/** + * @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; + unsigned char rxAckFlag; +} 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/yibaina_3061M/E7050_FOC/readme.md b/vendor/yibaina_3061M/E7050_FOC/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..556019956cf20786c3ae021de9abe7ceaa35cddb --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/readme.md @@ -0,0 +1,20 @@ +# E7050_foc + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的单电机双电阻采样的无感Foc应用 + +**【环境要求】** + +- 所有单板电源改制为演示用的24V低压,电机选用E7050 +- 电机(黄绿蓝)相线分别对应功率板上U/V/W通道接口 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 点击开发板按键启动电机 + +- 开发板蓝色电位器,可以调节电机转动的快慢。(5-29HZ) \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_FOC/user/generatecode/feature.h b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..715371be1e997b17c000b9d77eebcb18d838968e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/feature.h @@ -0,0 +1,94 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#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/yibaina_3061M/E7050_FOC/user/generatecode/main.h b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..40d65b1d6f31f1445aac968ab0626aeab2c4e93f --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/main.h @@ -0,0 +1,98 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +/* 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; + +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); + +/* 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/yibaina_3061M/E7050_FOC/user/generatecode/system_init.c b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..d49cd86016784553de8e7a45998524d3e24e3b24 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/generatecode/system_init.c @@ -0,0 +1,677 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_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); +} + +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); + + 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_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* 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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER0) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 1000000; + + g_timer0.baseAddress = TIMER0; + g_timer0.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer0.bgLoad = (load < 1) ? 0 : (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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer1.bgLoad = (load < 1) ? 0 : (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_BAUD_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 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/yibaina_3061M/E7050_FOC/user/main.c b/vendor/yibaina_3061M/E7050_FOC/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..d6ab767c3f2ad43dd09113ef5b0ca28d40a698ce --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/main.c @@ -0,0 +1,71 @@ +/** + * @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. + * @date 2025-04-14 14:05:10 + */ + +#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; +/* 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 diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..dea3ad66fde865889d8480d222b97f3900bd7dac --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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; /**< Motor start/stop status flag. */ + 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; /**< Current sampling mode setting: single resistor, double resistor. */ + 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; /**< Dual-resistance/three-resistance sampling SVPWM Handle. */ + R1SVPWM_Handle r1Sv; /**< Single-resistance phase-shifted SVPWM handle. */ + 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; /**< Motor protect status detection flag bit handle. */ +} MTRCTRL_Handle; + +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h new file mode 100644 index 0000000000000000000000000000000000000000..38c00b5ddbf9f63ab1a2e5b644eea55d634727ad --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h @@ -0,0 +1,76 @@ +/** + * @ 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" + +#if defined (CHIP_3061MNPICA) || defined (CHIP_3061MNPIKA) || defined (CHIP_3061MNNICA) || \ + defined (CHIP_3061MNNIKA) || defined (CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) || \ + defined (CHIP_3061MNPIK8) || defined (CHIP_3061MNNIK8) + + #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) || defined (CHIP_3066MNPIRH) || \ + defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) + + #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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6f38cccf3fb92d52b4874390805a520e255b2f --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..783bf21402d5d3f5d4bdc8dc5bd9ee425d0fbf21 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..19510c78b2d63a46ca51495d8ad028e351574d1d --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..8d4cb2161549ad4ba1c980752133f030574e8bc4 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h @@ -0,0 +1,108 @@ +/** + * @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 /* Capacitor charging time. */ + +#define INV_VOLTAGE_BUS 24.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. */ + +#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 /* SMO4TH PLL Bandwidth. */ +#define SMO4TH_KD 300.0f /* SMO4TH parameters KD. */ +#define SMO4TH_KQ 600.0f /* SMO4TH parameters KQ. */ +#define SMO4TH_SPD_FILTER_CUTOFF_FREQ 40.0f /* SMO4TH speed cutoff frequency of speed filter. */ + +/* User_Commond */ +#define CTRL_IF_CURR_AMP_A 0.7f /* IF control current amplitude. */ +#define USER_TARGET_SPD_HZ 100.0f /* User-defined target speed value. */ +#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 29.0f /* User-defined maximum speed value. */ +#define USER_MIN_SPD_HZ 5.0f /* User-defined minimum speed value. */ +#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 /* Current loop Q axis Kp. */ +#define CURRQAXIS_KI 20612.84f /* Current loop Q axis Ki. */ +#define CURRDAXIS_KP 3.477114f /* Current loop D axis Kp. */ +#define CURRDAXIS_KI 20612.84f /* Current loop D axis Ki. */ +/* Current loop PID output lower limit. */ +#define CURR_LOWERLIM (-INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) +/* Current loop PID output upper limit. */ +#define CURR_UPPERLIM (INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) + +#define SPD_KP 0.00505f /* Speed loop Kp. */ +#define SPD_KI 0.012f /* Speed loop Ki. */ +#define SPD_LOWERLIM (-0.105f) /* Speed loop PID output lower limit. */ +#define SPD_UPPERLIM 0.105f /* Speed loop PID output upper limit. */ + +/* 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 = 14, \ + .mtrRs = 10.1f, \ + .mtrLd = 0.010f, \ + .mtrLq = 0.010f, \ + .mtrPsif = 0.0f, \ + .mtrJ = 0.0f, \ + .maxElecSpd = 29.0f, \ + .maxCurr = 1.0f, \ + .busVolt = INV_VOLTAGE_BUS, \ +} + +/* Bus voltage sampling conversion factor. */ +#define ADC_UDC_COFFI 0.01289f /* 0.01289 = 3.3/4096*192/12. */ + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c new file mode 100644 index 0000000000000000000000000000000000000000..99766bdf9b3d4f161b1902708696cb0e75a4fc9c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h new file mode 100644 index 0000000000000000000000000000000000000000..104a5decba9eeb22375b63e4def4278af37d3573 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c new file mode 100644 index 0000000000000000000000000000000000000000..e97876b7c6ec522fa82c30cbe503e2ab8de288db --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h new file mode 100644 index 0000000000000000000000000000000000000000..365110e10c6cd8bd5207af61f0a87b6df226fa91 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..832cd1be005e463888b52c62a7af1fea37634f2a --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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 (1.0f) +/**< 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 (26.0f) /**<处于1级时,直流链路电压触发值(V)过高*/ +#define PROT_OVER_VOLT_BRK_ON2 (27.0f) /**< Over dc-link voltage trigger value (V) when in level 2. */ +#define PROT_OVER_VOLT_BRK_ON3 (28.0f) /**< Over dc-link voltage trigger value (V) when in level 3. */ +#define PROT_OVER_VOLT_BRK_ALL (30.0f) /**< Over dc-link voltage trigger value (V) when in level 4. */ +#define PROT_OVER_VOLT_RECY_DELTA (0.5f) /**<从保护状态恢复时的电压间隙(V)*/ +#define PROT_OVER_VOLT_LIMIT1_TIME_SEC (5.0f) /** 1; One-cycle mode: < 0.5 */ +#define POS_SNSR_IPD_INJ_PERIOD (4) + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..da4e56f89a51d39053fad4511bb799c91070df65 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..e9916fe491699bff3373bbc68b175b6db16d7cd7 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..b0541a2e2e37ba98e8b92e6334ab2cc940b72b6c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..0435156a0add386ec4b783f4d003f4178baa2ecf --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee4d2d240e66f7cfb0528b2d42d4c32ada0078 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d1e4bed11bec0d6d73aee54de36c365588898e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..184ba4a3ac712690e4f808f1464a65c74a387b52 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9d99a76c19f53a78ccc1257287eccfd1fc972c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/readme.md b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..98b2a068ddfaef196002273aaedc90123a0cd0de --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/readme.md @@ -0,0 +1,10 @@ +# pmsm_sensorless_2shunt_foc + +**【功能描述】** ++ 基于ECMCU105H/ECBMCU201MPC单板的单电机双电阻采样Foc应用 + +**【环境要求】** ++ 所有单板电源改制为演示用的12V低压,电机选用Gimbal GBM2804H-100T + +**【IDE配置方法】** ++ chipConfig中的Sample栏目里面选中pmsm sensorless 2shunt foc示例,然后点击生成代码即可 diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..9fc8afac32ecb5810db6758fb6acbca42a4c0f69 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..79bc3949d31044e401311212f30ff7c6ef3d136f --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c @@ -0,0 +1,950 @@ +/** + * @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}; + +/* 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.adc0Compensate = ADC0COMPENSATE; /* Phase-u current init adc shift trim value */ + g_mc.adc1Compensate = ADC1COMPENSATE; /* Phase-w current init adc shift trim value */ + + 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); + if (g_mc.sampleMode == DUAL_RESISTORS) { + SVPWM_Init(&g_mc.sv, INV_VOLTAGE_BUS * ONE_DIV_SQRT3); /* Dual resistors SVPWM init. */ + } else if (g_mc.sampleMode == SINGLE_RESISTOR) { + /* Single resistor SVPWM init. */ + 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. + * @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. + * @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. + * @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; + } + } + if (adcSampleTimes < 1.0f) { + adcSampleTimes = 1.0f; /* Prevent divide-by-zero errors */ + } + 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. + * @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. + * @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. + * @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 = 0.0f; + /* 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); + static float potentiomitorAdcValue = 0.0f; + static float spdCmdHz = 0; + static float spdCmdHzLast = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHzLast init value */ + HAL_ADC_SoftTrigSample(&ADCPTT_HANDLE, ADCPTTSOCNUM); + BASE_FUNC_DELAY_US(10); /* Delay 10 us. */ + potentiomitorAdcValue = (float)HAL_ADC_GetConvResult(&ADCPTT_HANDLE, ADCPTTSOCNUM); + /* 4045.0 is adc sample max value of potentiomitor, convert max spd to 180.25Hz */ + spdCmdHz = potentiomitorAdcValue / 4045.0f * USER_MAX_SPD_HZ; + if (Abs(spdCmdHzLast - spdCmdHz) < 1.0f) { /* Ignore changes less than 1. */ + return; + } + spdCmdHzLast = spdCmdHz; + if (spdCmdHz < USER_MIN_SPD_HZ) { /* 35.0 is spdCmdHz lower limit */ + spdCmdHz = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHz lower limit */ + } + if (spdCmdHz > g_mc.mtrParam.maxElecSpd) { /* spdCmdHz upper limit */ + spdCmdHz = g_mc.mtrParam.maxElecSpd; /* spdCmdHz upper limit */ + } + if (g_mc.spdAdjustMode == CUST_SPEED_ADJUST) { + g_mc.spdCmdHz = spdCmdHz; + } +} + +/** + * @brief System timer ISR for Motor Statemachine CallBack function. + * @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. */ + 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 */ + g_mc.readCurrUvwCb = ReadCurrUvw; + g_mc.setPwmDutyCb = SetPwmDutyCp; + g_mc.setADCTriggerTimeCb = SetADCTriggerTime; +} + +/** + * @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); + } + } +} + +/** + * @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); + + /* Disable PWM output before startup. */ + 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); + while (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 */ + 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; + } + } + return 0; +} diff --git a/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c new file mode 100644 index 0000000000000000000000000000000000000000..7c4f75252f9cb7a7fd3b2452ad276e8074519121 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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); + float pllBdw = 0.0f; + switch (cmdCode) { + case SET_SMO1TH_PLL_BDW: /* Set the bandwidth. */ + pllBdw = rxData->data[DATA_SEGMENT_THREE].typeF; + smoHandle->pll.pi.kp = 2.0f * pllBdw; /* kp = 2.0f * pllBdw */ + smoHandle->pll.pi.ki = pllBdw * pllBdw; /* ki = pllBdw * pllBdw */ + ackCode = 0X0A; + CUST_AckCode(g_uartTxBuf, ackCode, 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) +{ + float pllBdw = rxData->data[DATA_SEGMENT_TWO].typeF; + smo4thHandle->pll.pi.kp = (2.0f) * pllBdw; /* kp = 2.0f * pllBdw */ + smo4thHandle->pll.pi.ki = pllBdw * pllBdw; + ackCode = 0X11; + CUST_AckCode(g_uartTxBuf, ackCode, 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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h new file mode 100644 index 0000000000000000000000000000000000000000..60fe69bb966d5f398468c8093e266796391de4e5 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c new file mode 100644 index 0000000000000000000000000000000000000000..58bf15a7071e2dbfbea0a799bfd5eebe2d9f8403 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h new file mode 100644 index 0000000000000000000000000000000000000000..056f8d7310eb14335c256933e8d998bf09919cc6 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c new file mode 100644 index 0000000000000000000000000000000000000000..56f0c0bb3fa394c355dcbef7f6387270bf31dd67 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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_WriteDMA(&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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..900a00d8065b0154f3883d213be12f63610d0be1 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c new file mode 100644 index 0000000000000000000000000000000000000000..df5e918648921817e0e0fd5c9d98c5c0ee6bcb26 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c @@ -0,0 +1,184 @@ +/** + * @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) + +/* 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. + * @retval None. + */ +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; + uartFrame->rxAckFlag = 0; +} + +/** + * @brief Set Dma status. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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 Uart Dma interupt callback func. + * @param handle Uart handle. + * @retval None. + */ +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; + /* Received information answered, information update reserved. */ + if (g_uartFrame.rxAckFlag == 1) { + g_uartFrame.uartItTxFlag = 1; + g_uartFrame.rxAckFlag = 0; + } + 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 Read CallBack Function. + * @param handle Uart handle. + * @retval None. + */ +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. + * @retval None. + */ +void UartRecvInit(void) +{ + /* Uart reception initialization */ + FrameRecvClear(&g_uartFrame); + HAL_UART_ReadIT(&g_uart0, &g_uartFrame.rxData, 1); +} + +/** + * @brief Uart Read Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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.rxAckFlag = 1; + g_uartFrame.rxLen = 0; + } + } + g_uartFrame.frameFlag = 0; +} + +/** + * @brief Uart Write Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h new file mode 100644 index 0000000000000000000000000000000000000000..f1f8f89951fd2ab017f9ad6082a2542ca925aaaa --- /dev/null +++ b/vendor/yibaina_3061M/E7050_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h @@ -0,0 +1,47 @@ +/** + * @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; + unsigned char rxAckFlag; +} 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/yibaina_3061M/E7050_Six_Step_Wave/readme.md b/vendor/yibaina_3061M/E7050_Six_Step_Wave/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0414d5efcf9480603fa9455a4c7fc3ccb6cf2956 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/readme.md @@ -0,0 +1,20 @@ +# E7050_Six_Step_Wave + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的反电动势采样的无感电机六步方波调速系统应用 + +**【环境要求】** + +- 所有单板电源改制为演示用的24V低压,电机选用E7050 +- 电机(黄绿蓝)相线分别对应功率板上U/V/W通道接口 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 点击开发板按键启动电机 + +- 开发板蓝色电位器,可以调节电机转动的快慢。(15-58.8HZ) \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/feature.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..13108bb335a3fe189a609d37b01dc36e0b3d37b8 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/feature.h @@ -0,0 +1,94 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +#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/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/main.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..55b93f82824132029e9c0ce2344e498211bb5c26 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/main.h @@ -0,0 +1,84 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +/* 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 "crg.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 SYS_LED_PIN GPIO_PIN_3 +#define SYS_LED_HANDLE g_gpio2 +#define GpioStartStop_PIN GPIO_PIN_4 +#define GpioStartStop_HANDLE g_gpio2 + +extern ACMP_Handle g_acmp0; +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 GPIO_Handle g_gpio1; +extern GPIO_Handle g_gpio2; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void MotorStatemachineCallBack(void *handle); +void TIMER1_DMAOverFlow_InterruptProcess(void *handle); +void MotorCarrierProcessCallback(void *aptHandle); +void MotorSysErrCallback(void *aptHandle); + +void MotorStartStopKeyCallback(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/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/system_init.c b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..76ec601ac147b08a302eba9c849a507048421353 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/generatecode/system_init.c @@ -0,0 +1,530 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_RATE 115200 + +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 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_ADCINA11; /* PIN9(ADC AIN11) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM5, &socParam); + + socParam.adcInput = ADC_CH_ADCINA12; /* PIN10(ADC AIN12) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM2, &socParam); + + socParam.adcInput = ADC_CH_ADCINA10; /* PIN8(ADC AIN10) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_5CLK; /* adc sample total time 5 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM9, &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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt0.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt0.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt0.adcTrg.cntCmpSOCA = 6000; /* 6000 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_CMPA_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_CMPC_UP; + 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, 6); /* 6 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt1.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt1.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt1.adcTrg.cntCmpSOCA = 1; /* 1 is count compare point of ADC trigger source SOCA when using CMPA */ + g_apt1.adcTrg.trgSrcSOCA = APT_CS_SRC_CNTR_ZERO; + g_apt1.adcTrg.trgScaleSOCA = 1; + + g_apt1.adcTrg.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt1.adcTrg.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + + 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt2.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 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); +} + +static void GPIO_Init(void) +{ + 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(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_LOW_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_FALL_EDGE); + + HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* gpio interrupt enable */ + + return; +} + +__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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer1.bgLoad = (load < 1) ? 0 : (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, 2); /* 2 is priority value */ + IRQ_EnableN(IRQ_TIMER1); +} + +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} + +static void IOConfig(void) +{ + SYSCTRL0->SC_SYS_STAT.BIT.update_mode = 0; + SYSCTRL0->SC_SYS_STAT.BIT.update_mode_clear = 1; + /* Config PIN9 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_5_AS_ADC_AIN11); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_5_AS_ADC_AIN11, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_5_AS_ADC_AIN11, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_5_AS_ADC_AIN11, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_5_AS_ADC_AIN11, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN10 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_3_AS_ADC_AIN12); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_3_AS_ADC_AIN12, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_3_AS_ADC_AIN12, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_3_AS_ADC_AIN12, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_3_AS_ADC_AIN12, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN8 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_6_AS_ADC_AIN10); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_6_AS_ADC_AIN10, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_6_AS_ADC_AIN10, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_6_AS_ADC_AIN10, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_6_AS_ADC_AIN10, 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 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 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 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 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 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 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 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(); + UART0_Init(); + ACMP0_Init(); + APT0_Init(); + APT1_Init(); + APT2_Init(); + ADC0_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/yibaina_3061M/demo/sample_gpio_key/main.c b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/main.c similarity index 92% rename from vendor/yibaina_3061M/demo/sample_gpio_key/main.c rename to vendor/yibaina_3061M/E7050_Six_Step_Wave/user/main.c index 10f82fbe10df696360782732d64fa1acb993e5a2..b8775e1a226ea9107a41fe70881de9b369d358ff 100644 --- a/vendor/yibaina_3061M/demo/sample_gpio_key/main.c +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/main.c @@ -18,17 +18,25 @@ * @file main.c * @author MCU Driver Team * @brief Main program body. + * @date 2025-04-23 14:18:03 */ #include "typedefs.h" #include "feature.h" -#include "gpio_key_sample.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; +TIMER_Handle g_timer1; UART_Handle g_uart0; +APT_Handle g_apt0; +APT_Handle g_apt1; +APT_Handle g_apt2; +ADC_Handle g_adc0; +GPIO_Handle g_gpio1; GPIO_Handle g_gpio2; /* USER CODE BEGIN 1 */ /* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ @@ -39,7 +47,7 @@ int main(void) /* USER CODE BEGIN 2 */ /* 建议用户放置初始化代码或启动代码等 */ /* USER CODE END 2 */ - GPIO_KeySample(); + MotorMainProcess(); /* USER CODE BEGIN 3 */ /* 建议用户放置初始配置代码 */ /* USER CODE END 3 */ diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..94898dd5ab96eee7b091a53c7357319f0a59210c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c @@ -0,0 +1,562 @@ +/** + * @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 for ECBMCU201MPC board. + * @details BLDC six-step application based on the ECBMCU201MPC board + * 1) Motor model is Gimbal GBM2804H-100T. + * 2) Select the bldc six-step sensorless example in the sample column + of chipConfig and click Generate Code. + * 3) It's power supply must be changed to 12V. + */ + +#include "debug.h" +#include "mcs_assert.h" +#include "mcs_user_config.h" +#include "mcs_status.h" +#include "mcs_carrier.h" +#include "mcs_motor_process.h" + +/*------------------------------- Macro Definition -----------------------------------------------*/ +#define US_PER_MS 1000 +#define APT_FULL_DUTY 1.0f + +/* Motor control handle for bldc */ +static MtrCtrlHandle g_mc; + +static APT_RegStruct* g_aptCp[PHASE_MAX_NUM] = {BRIDGE_CTR_APT_U, BRIDGE_CTR_APT_V, BRIDGE_CTR_APT_W}; + +/** + * @brief Initialzer of system tick. + * @param mtrCtrl Motor control struct handle. + * @retval None. + */ +static void TimerTickInit(MtrCtrlHandle *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 Read the ADC current sampling value of the compressor. + * @param CurrUvw Three-phase current. + * @retval None. + */ +static void ReadBemfUVWMotor(UVWBemf *bemfUVW) +{ + MCS_ASSERT_PARAM(bemfUVW != NULL); + bemfUVW->u = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_U_SOC_NUM)&0xFFF); + bemfUVW->v = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_V_SOC_NUM)&0xFFF); + bemfUVW->w = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_W_SOC_NUM)&0xFFF); +} + +/** + * @brief Init motor control task. + * @retval None. + */ +static void TSK_InitMotor(void) +{ + /* Initialize target speed. */ + g_mc.spdCmdHz = SDP_TARGET_VALUE; + /* zeroPoint = IN_VOLTAGE_BUS / 2.0; 4095/3.3 :ADC value corresponding to 1 V */ + g_mc.zeroPoint = ((((float)IN_VOLTAGE_BUS / 2.0) * VOL_DIVIDER_COEFFICIENT) * 4095 / 3.3); + g_mc.pwmDuty = FORCE_DRAG_MINDUTY; + + /* Sets the number of sample filtering times for zero-crossing sampling. */ + g_mc.sysVar.bemfFilterCnt = FILTER_COUNT; + g_mc.sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + + g_mc.stateMachine = FSM_IDLE; + g_mc.aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Speed management initialization. */ + RMG_Init(&g_mc.spdRmg, CTRL_SYSTICK_PERIOD, USER_SPD_SLOPE); /* Init speed slope */ + TimerTickInit(&g_mc); + + /* Pid control parameter initialization. */ + g_mc.spdPi.kp = SPD_PID_KP; + g_mc.spdPi.ki = SPD_PID_KI; + g_mc.spdPi.ts = SPD_PID_TS; + g_mc.spdPi.upperLimit = APT_DUTYLIMIT_MAX; + g_mc.spdPi.lowerLimit = APT_DUTYLIMIT_MIN; + + /* BLDC six-step control initialization. */ + g_mc.stepCtrl.phaseStep = STEP1; + g_mc.stepCtrl.controlApt.u = &g_apt0; + g_mc.stepCtrl.controlApt.v = &g_apt1; + g_mc.stepCtrl.controlApt.w = &g_apt2; +} + + +/** + * @brief Software Initialization. + * @retval None. + */ +static void InitSoftware(void) +{ + TSK_InitMotor(); + + g_mc.readBemfUVW = ReadBemfUVWMotor; +} + +/** + * @brief Enable three-phase pwm output. + * @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 = 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 = 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 强制转子对准原位。 + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceAlign(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + MotorPwmOutputEnable(g_aptCp); + mtrCtrl->stepCtrl.phaseStep = STEP6; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->stepCtrl.phaseStep = STEP1; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); +} + +/** + * @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_WAIT_STOP; + } +} + +/** + * @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 int maxDutyCnt) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + MCS_ASSERT_PARAM(maxDutyCnt != 0); + unsigned int dutyCnt; + dutyCnt = maxDutyCnt * APT_FULL_DUTY; + /* Open the three-phase lower pipe */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = aptAddr[i]; + aptx->TC_REFC.BIT.rg_cnt_refc = dutyCnt; + aptx->TC_REFD.BIT.rg_cnt_refd = dutyCnt; + } +} + +/** + * @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(MtrCtrlHandle *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 Clear historical values of all controller before start-up. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ClearBeforeStartup(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Clear bemf parameters. */ + mtrCtrl->bemf.u = 0; + mtrCtrl->bemf.v = 0; + mtrCtrl->bemf.w = 0; + + /* Clear tickcnt. */ + mtrCtrl->msTickCnt = 0; + + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + + /* Clear spd parameters. */ + mtrCtrl->spdEstHz = 0; + mtrCtrl->spdRefHz = 0; + + mtrCtrl->stepCtrl.phaseStep = STEP1; + + mtrCtrl->sysTickCnt = 0; + + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + mtrCtrl->sysVar.changePhaseFlag = 0; + mtrCtrl->sysVar.firstEventFilterFlag = 0; + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 0; + for (int i = 0; i < STEP_MAX_NUM; i++) { + mtrCtrl->sysVar.stepTime[i] = 0; + } + /* RMG CLEAR */ + RMG_Clear(&mtrCtrl->spdRmg); /* Clear the history value of speed slope control */ + /* SPDCTRL CLEAR */ + PID_Clear(&mtrCtrl->spdPi); +} + +/** + * @brief Check bootstrap capacitor charge time. + * @param mtrCtrl The motor control handle. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckBootstrpCapChargeTime(MtrCtrlHandle *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) { + /* Update Status. */ + *stateMachine = FSM_CLEAR; + } +} + +/** + * @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 Deceleration control phase before stop. + * @param mtrCtrl The motor control handle. + * @param statusReg Motor Control Status. + * @param targetSpd Deceleration target value. + * @param switchSpd Switch to stop state speed. + * @retval None. + */ +static void DecelerateSpeed(MtrCtrlHandle *mtrCtrl, FsmState *stateMachine, float targetSpd, float switchSpd) +{ + /* Reduce speed before stop. */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, targetSpd); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + if (mtrCtrl->spdRefHz <= switchSpd) { /* Maximum speed for switching to the FSM_STOP state */ + *stateMachine = FSM_STOP; + } +} + +/** + * @brief System timer tick task. + * @param mtrCtrl The motor control handle. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void TSK_SystickIsr(MtrCtrlHandle *mtrCtrl, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + SysStatusReg *statusReg = &mtrCtrl->statusReg; + volatile FsmState *stateMachine = &mtrCtrl->stateMachine; + mtrCtrl->msTickCnt++; + /* Pre-processing of motor status. */ + MotorStatePerProc(statusReg, stateMachine); + /* statemachine */ + switch (*stateMachine) { + case FSM_IDLE: + CheckSysCmdStart(mtrCtrl, aptAddr, statusReg, (FsmState *)stateMachine); + break; + case FSM_CAP_CHARGE: + /* Bootstrap Capacitor Charging Timing */ + CheckBootstrpCapChargeTime(mtrCtrl, (FsmState *)stateMachine); + break; + case FSM_CLEAR: + /* Clearing control parameters. */ + ClearBeforeStartup(mtrCtrl); + /* Rotor alignment. */ + ForceAlign(mtrCtrl); + *stateMachine = FSM_STARTUP; + break; + case FSM_STARTUP: + /* Forced drag. */ + break; + case FSM_RUN: + /* Speed ramp control */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + break; + case FSM_WAIT_STOP: + /* 5.0f : maximum speed for switching to the FSM_STOP state */ + DecelerateSpeed(mtrCtrl, (FsmState *)stateMachine, 0.0f, 5.0f); + break; + case FSM_STOP: + MotorPwmOutputDisable(aptAddr); + SysRunningClr(statusReg); + *stateMachine = FSM_IDLE; + break; + case FSM_FAULT: + /* Overcurrent state */ + CheckOverCurrentState(statusReg, (FsmState *)stateMachine); + break; + default: + break; + } +} + +/** + * @brief Overcurrent protection. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorSysErrCallback(void *aptHandle) +{ + /* Overcurrent protection callback function. */ + BASE_FUNC_UNUSED(aptHandle); + MotorPwmOutputDisable(g_aptCp); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_U], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_V], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_W], APT_OC_COMBINE_EVENT_A1); + /* Status setting error */ + SysErrorSet(&g_mc.statusReg); + DBG_PRINTF("APT error! \r\n"); + HAL_GPIO_SetValue(&g_gpio2, GPIO_PIN_3, GPIO_LOW_LEVEL); +} + +/** + * @brief Motor blockage protection function. + * @retval None. + */ +static void MotorBlockageProtect(void) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= g_mc.sysVar.lastZeroPoint) + ? currentTick - g_mc.sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - g_mc.sysVar.lastZeroPoint + currentTick + 1; + if (intervalTick > SYSTICK_GetCRGHZ()) { + MotorPwmOutputDisable(g_aptCp); + SysErrorSet(&g_mc.statusReg); + g_mc.spdEstHz = 0; + return; + } +} + +/** + * @brief Carrier Interruption. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorCarrierProcessCallback(void *aptHandle) +{ + BASE_FUNC_UNUSED(aptHandle); + /* USER CODE BEGIN APT0_TIMER_INTERRUPT */ + MCS_CarrierProcess(&g_mc); + if (g_mc.stateMachine == FSM_RUN || g_mc.stateMachine == FSM_WAIT_STOP) { + MotorBlockageProtect(); + } + /* USER CODE END APT0_TIMER_INTERRUPT */ +} + +/** + * @brief Change phase delay callback function. + * @param handle The TIMER1 Handle. + * @retval None. + */ +void MotorStatemachineCallBack(void *handle) +{ + /* TIMER1CallbackFunction */ + BASE_FUNC_UNUSED(handle); + TSK_SystickIsr(&g_mc, g_aptCp); +} + +/** + * @brief Check Potentiometer Value and adjust speed. + * @param None. + * @retval None. + */ +static void AdjustSpeedFunction(void) +{ + static unsigned int potentiomitorAdcValue = 0; + static float spdCmdHz = 0; + static float spdCmdHzLast = SDP_MAX_VALUE; + HAL_ADC_SoftTrigSample(&ADC_HANDLE, ADC_SOC_NUM9); /* Get the speed adjustment resistance. */ + potentiomitorAdcValue = HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_SOC_NUM9); + /* 4045.0 is adc sample max value of potentiomitor */ + spdCmdHz = (float)potentiomitorAdcValue / 4045.0 * SDP_MAX_VALUE; + if (spdCmdHz < SDP_MIN_VALUE) { /* Speed protection. */ + spdCmdHz = SDP_MIN_VALUE; + } + if (spdCmdHz > SDP_MAX_VALUE) { + spdCmdHz = SDP_MAX_VALUE; + } + float delta = spdCmdHzLast > spdCmdHz ? (spdCmdHzLast - spdCmdHz) : (spdCmdHz - spdCmdHzLast); + /* 1.0 : If the speed fluctuation is less than 1.0Hz, no change is made. */ + if (delta < 1.0) { + return; + } + spdCmdHzLast = spdCmdHz; + g_mc.spdCmdHz = spdCmdHz; +} + +/** + * @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 (SysIsRunning(&g_mc.statusReg)) { /* stop apt output, motor is off status */ + SysCmdStopSet(&g_mc.statusReg); + } else { /* start apt output, motor is on status */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + SysCmdStartSet(&g_mc.statusReg); + } + } +} + +/** + * @brief User application entry. + * @retval BSP_OK. + */ +int MotorMainProcess(void) +{ + SystemInit(); + /* System Initialization. */ + unsigned int tickNum100Ms = 200; /* 100ms tick */ + static unsigned int tickCnt100Ms = 0; + unsigned int tickNum500Ms = 1000; /* 500ms tick */ + static unsigned int tickCnt500Ms = 0; + + HAL_TIMER_Start(&g_timer1); + /* Disable PWM output before startup. */ + MotorPwmOutputDisable(g_aptCp); + InitSoftware(); + /* Start the PWM clock. */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + + while (true) { + if (g_mc.msTickCnt - tickCnt100Ms >= tickNum100Ms) { + tickCnt100Ms = g_mc.msTickCnt; + /* User Code 100ms Event */ + AdjustSpeedFunction(); + } + if (g_mc.msTickCnt - tickCnt500Ms >= tickNum500Ms) { + if (SysIsError(&g_mc.statusReg) == true) { + break; + } + /* The LED blinks when no status is not error. */ + HAL_GPIO_TogglePin(&SYS_LED_HANDLE, SYS_LED_PIN); + tickCnt500Ms = g_mc.msTickCnt; + } + } + return 0; +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..a2fdeb2c62a9185aa9d9d08c3408e0e88486066c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h @@ -0,0 +1,47 @@ +/** + * @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 ECBMCU201MPC board. + */ +#ifndef McuMagicTag_MCS_MOTOR_PROCESS_H +#define McuMagicTag_MCS_MOTOR_PROCESS_H + +#include "main.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/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..f193532a63ce3d468aaac9e35791912761e5d47e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h @@ -0,0 +1,94 @@ +/** + * @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_config.h + * @author MCU Algorithm Team + * @brief This file provides config macros for ECBMCU201MPC app. + */ +#ifndef McuMagicTag_MCS_CONFIG_H +#define McuMagicTag_MCS_CONFIG_H + +#if defined(CHIP_3061MNPICA) || defined(CHIP_3061MNNICA) || defined(CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) +#define ADC_U_SOC_NUM ADC_SOC_NUM2 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM6 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 +#define ADC_HANDLE g_adc0 +#endif + +#if defined (CHIP_3066MNPIRH) || defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) +#define ADC_U_SOC_NUM ADC_SOC_NUM3 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM7 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 + +#define ADC_HANDLE g_adc2 +#endif + +#define APT_PWM_FREQ 12000 /* PWM frequency 12K Hz. */ +#define CTRL_CURR_PERIOD (1.0f / APT_PWM_FREQ) /* carrier ISR period (S) */ +#define CTRL_CURE_PERIOD_US 83 + +#define SYSTICK_PERIOD_US 500u /* systick period. unit : us */ + +#define INV_CAP_CHARGE_MS 3u /* Bootstrap capacitor charge time. unit : ms */ + +#define CTRL_SYSTICK_PERIOD 0.0005f /* systick control period, 500us */ + +#define USER_SPD_SLOPE 60.0f /* slope of velocity change */ + +#define IN_VOLTAGE_BUS 24 /* Motor input voltage */ +#define POLES 14 /* 电机磁极对数 */ +#define MATH_PI 3.14 /* Pi */ +#define MOTOR_K 1.62 /* 转矩系数 */ + +#define RAMP_STP 60 /* Slope of forced draging acceleration */ +#define RAMP_DUTY_PWM 0.5 /* 1.0% */ + +#define FORCE_DRAG_MINDUTY 15 /* APT minimum duty cycle during forced drag */ +#define FORCE_DRAG_MAXDUTY 20 /* APT maximum duty cycle during forced drag */ + +#define DRAG_START_INTERVAL 1000 /* Force drag change phase time */ +#define DRAG_STOP_INTERVAL 400 /* Force drag change phase time */ + +/* Parameters of the motor in the RUN */ +#define FILTER_COUNT 3 /* Filter Times */ +#define PHASE_OFFSET 9000 /* Phase delay due to filtering */ + +#define APT_DUTYLIMIT_MAX 99.9 /* 输出APT的最大占空比 */ +#define APT_DUTYLIMIT_MIN 8.0 /* Minimum duty cycle of the output APT */ + +#define BRIDGE_CTR_APT_U APT0 /* APT address that controls the U phase */ +#define BRIDGE_CTR_APT_V APT1 /* APT address that controls the V phase */ +#define BRIDGE_CTR_APT_W APT2 /* APT address that controls the W phase */ + +#define SDP_MAX_VALUE 58.8 /* 最大相位变化频率 */ +#define SDP_MIN_VALUE 15.0 /* Minimum change phase frequency */ +#define SDP_TARGET_VALUE 58.8 /* 目标相位变化频率 */ + +/* SPD PID Param */ +#define SPD_PID_KP 0.9 /* P parameter of PID control */ +#define SPD_PID_KI 40 /* I parameter of PID control */ +#define SPD_PID_TS 0.0005 /* TS parameter of PID control cycle */ + +#define OP_TO_CL_INTERGRAL 8.0 /* Open-loop switching closed-loop integral term to prevent sudden current change. */ + +#define VOL_DIVIDER_COEFFICIENT 0.09091f /* Division coefficient of the zero-crossing detection sampling circuit */ + +#define SPD_FILTER_FC 30 + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..7779fbef2e3eee99fb209f617bb4d3f7d923309d --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c @@ -0,0 +1,224 @@ +/** + * @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_user_config.h" +#include "mcs_assert.h" +#include "debug.h" + +#define S_TO_US 1000000 +#define S_TO_SYSTICK 100000000 + +/** + * @brief Sets the duty cycle of the H-bridge APT. + * @param aptHandle APT module handle. + * @param duty PWM duty. Range: 0.1 ~ 99.9. + * @retval None. + */ +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(duty > 0); + /* Set pwm duty of uvw pahse */ + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.u, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.v, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.w, duty); +} + +/** + * @brief Strong drag start. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceDragAcc(MtrCtrlHandle *mtrCtrl) +{ + /* Verifying Parameters. */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + unsigned int voltageDValue; + unsigned int dragChangeFreq; + unsigned int timerperiod; + unsigned int freqLast; + unsigned int aptCountsOneUs; + + mtrCtrl->sysVar.accTimeCnt++; + if (mtrCtrl->sysVar.accTimeCnt < mtrCtrl->sysVar.dragChangePhaseTime) { + return; + } + + mtrCtrl->sysVar.accTimeCnt = 0; + /* Step 1: Calculate the voltage difference. */ + voltageDValue = IN_VOLTAGE_BUS * RAMP_DUTY_PWM; + /* Step 2: Calculate the commutation frequency. */ + freqLast = S_TO_US / (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US); + dragChangeFreq = voltageDValue * STEP_MAX_NUM * POLES / (MOTOR_K * 2 * MATH_PI) + freqLast; /* 2*PI = 360° */ + /* Step 3: Convert the commutation frequency to the commutation count value. */ + timerperiod = mtrCtrl->stepCtrl.controlApt.u->waveform.timerPeriod * CTRL_CURE_PERIOD_US; + mtrCtrl->sysVar.dragChangePhaseTime = S_TO_US / (timerperiod * dragChangeFreq); + + /* Determine whether the change phase speed has reached the speed of stopping forced drag. */ + if (mtrCtrl->sysVar.dragChangePhaseTime < DRAG_STOP_INTERVAL) { + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_STOP_INTERVAL; + mtrCtrl->sysVar.accTimeCnt = 0; + mtrCtrl->sysVar.bemfFilterCnt = 0; + mtrCtrl->stateMachine = FSM_RUN; + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); + mtrCtrl->spdPi.integral = OP_TO_CL_INTERGRAL; + } + + /* Shorten the time interval of forced drag change phase. */ + mtrCtrl->pwmDuty += RAMP_DUTY_PWM; + aptCountsOneUs = HAL_CRG_GetIpFreq(APT0_BASE) / S_TO_US; + mtrCtrl->sysVar.waitTime = (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US * aptCountsOneUs) >> 1; + /* Change phase time is 2 the waiting time. */ + mtrCtrl->spdRefHz = (float)(HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime * 2)) / STEP_MAX_NUM; + mtrCtrl->spdEstHz = mtrCtrl->spdRefHz; + mtrCtrl->spdRmg.yLast = mtrCtrl->spdRefHz; + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + /* Limiting the PWM Duty Cycle Range. */ + if (mtrCtrl->pwmDuty > FORCE_DRAG_MAXDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MAXDUTY; + } + if (mtrCtrl->pwmDuty < FORCE_DRAG_MINDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + } + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); +} + +/** + * @brief Zero-crossing filter. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroSampleFilter(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->sysVar.bemfFilterCnt++; + /* Filter the number of samples. */ + if (mtrCtrl->sysVar.bemfFilterCnt >= FILTER_COUNT) { + mtrCtrl->sysVar.bemfFilterCnt = 0; + unsigned int currentTick = DCL_SYSTICK_GetTick(); + if (mtrCtrl->sysVar.firstEventFilterFlag == 0) { + mtrCtrl->sysVar.lastZeroPoint = currentTick; + mtrCtrl->sysVar.changePhaseFlag = 1; + mtrCtrl->sysVar.firstEventFilterFlag = 1; + return; + } + /* Calculate the time interval between the last zero crossing. */ + mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] = currentTick >= mtrCtrl->sysVar.lastZeroPoint + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + mtrCtrl->sysVar.stepTimeNum++; + /* Wait time is half the interval. */ + mtrCtrl->sysVar.waitTime = mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] >> 1; + mtrCtrl->sysVar.waitTime -= PHASE_OFFSET; + mtrCtrl->sysVar.lastZeroPoint = currentTick; + /* Update flag. */ + mtrCtrl->sysVar.changePhaseFlag = 1; + } +} + +/** + * @brief Back EMF zero crossing check. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroCheck(MtrCtrlHandle *mtrCtrl) +{ + /* The step corresponds to different conditional judgments. */ + unsigned int bemfCheckTable[STEP_MAX_NUM] = {mtrCtrl->bemf.w < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.w > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u > mtrCtrl->zeroPoint ? 1 : 0}; + + if (bemfCheckTable[mtrCtrl->stepCtrl.phaseStep] == 1) { + BemfZeroSampleFilter(mtrCtrl); + } +} + +/** + * @brief Change phase and speed estimation. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ChangePhase(MtrCtrlHandle *mtrCtrl) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= mtrCtrl->sysVar.lastZeroPoint) + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + /* Start average filtering when the number of recorded data reaches six. */ + if (mtrCtrl->sysVar.stepTimeNum >= STEP_MAX_NUM) { + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 1; + } + /* If the accumulated time is greater than the waiting commutation time, commutation is performed. */ + if (intervalTick > mtrCtrl->sysVar.waitTime) { + if (mtrCtrl->sysVar.stepTimeFilterEnable) { /* 6-step commutation time averaging if filtering is enabled. */ + unsigned int totalTime = mtrCtrl->sysVar.stepTime[STEP1] + mtrCtrl->sysVar.stepTime[STEP2] + + mtrCtrl->sysVar.stepTime[STEP3] + mtrCtrl->sysVar.stepTime[STEP4] + + mtrCtrl->sysVar.stepTime[STEP5] + mtrCtrl->sysVar.stepTime[STEP6]; + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / totalTime; + } else { + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime << 1) / STEP_MAX_NUM; + } + /* Change phase. */ + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + mtrCtrl->sysVar.changePhaseFlag = 0; + } +} + +/** + * @brief Zero-crossing detection and change phase + * @param mtrCtrl The motor control handle. + * @retval None. + */ +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + /* Offset value of the calibration value of the three-phase current */ + + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + ForceDragAcc(mtrCtrl); /* Forced drag. */ + break; + + case FSM_RUN: + case FSM_WAIT_STOP: + mtrCtrl->readBemfUVW(&mtrCtrl->bemf); + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + if (mtrCtrl->sysVar.changePhaseFlag) { + /* Change phase process. */ + ChangePhase(mtrCtrl); + } else { + /* Zero-crossing detection procedure. */ + BemfZeroCheck(mtrCtrl); + } + break; + + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..05fc26667e96b59288aba49344f448a3bf243816 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h @@ -0,0 +1,91 @@ +/** + * @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_six_step.h" +#include "mcs_ramp_mgmt.h" +#include "mcs_spd_ctrl.h" +#include "mcs_fsm.h" + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + unsigned int u; /**< Component u of the three-phase static coordinate frame variable. */ + unsigned int v; /**< Component v of the three-phase static coordinate frame variable. */ + unsigned int w; /**< Component w of the three-phase static coordinate frame variable. */ +} UVWBemf; + +typedef void (*ReadBemf)(UVWBemf *bemfUVW); + +/** + * @brief The definition of the systematic global variables + */ +typedef struct { + unsigned char changePhaseFlag; /**< Flag indicating that delay change phase is required */ + unsigned char firstEventFilterFlag; /**< First zero-crossing event filtering flag. */ + unsigned int dragChangePhaseTime; /**< Interval for forced drag acceleration */ + unsigned int accTimeCnt; /**< Acceleration time count */ + + unsigned int bemfFilterCnt; /**< Number of sample filtering times for zero-crossing detection. */ + + unsigned int lastZeroPoint; /**< Time of the last zero point */ + unsigned int waitTime; /**< Time to wait for change phase */ + unsigned int stepTime[STEP_MAX_NUM]; /**< Record the time spent on each step */ + unsigned int stepTimeNum; /**< Number of data records in the steptime array. */ + unsigned int stepTimeFilterEnable; +} SysVariable; + +typedef struct { + volatile float spdCmdHz; /**< Set target change phase frequency */ + float spdRefHz; /**< Command values after speed ramp management */ + float spdEstHz; /**< Actual change phase frequency of feedback */ + float pwmDuty; /**< APT duty cycle */ + unsigned int zeroPoint; /**< Adc value of zero point */ + + unsigned short aptMaxcntCmp; /**< Apt Maximum Comparison Count */ + + unsigned short sysTickCnt; /**< System Timer Tick Count */ + unsigned short capChargeTickNum; /**< Bootstrap Capacitor Charge Tick Count */ + unsigned short msTickNum; /**< Number of ticks corresponding to 1 ms */ + volatile unsigned int msTickCnt; /**< Millisecond-level counter, which can be used in 1-ms and 5-ms tasks. */ + + RMG_Handle spdRmg; /**< Ramp management struct for the speed controller input reference */ + PID_Handle spdPi; /**< PI controller struct in the speed controller. */ + + UVWBemf bemf; /**< Three-phase back electromotive force */ + SixStepHandle stepCtrl; /**< Control structure of six-step square wave */ + + SysVariable sysVar; /**< System Variables */ + SysStatusReg statusReg; /**< System Status */ + FsmState stateMachine; /**< BLDC Motor Control State Machine */ + + ReadBemf readBemfUVW; /**< Function interface for obtaining the three-phase electromotive force */ +} MtrCtrlHandle; + +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl); + +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h new file mode 100644 index 0000000000000000000000000000000000000000..b3c79ea2c8fccfc6f797d664899b8a249118aa3d --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h @@ -0,0 +1,55 @@ +/** + * @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_fsm.h + * @author MCU Algorithm Team + * @brief This file provides the definition of finite statemachine (FSM). + */ + +#ifndef McuMagicTag_MCS_FSM_H +#define McuMagicTag_MCS_FSM_H + +/** + * @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; + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c new file mode 100644 index 0000000000000000000000000000000000000000..c86e609c8e3512ec0e0569c06aae5f38afff8ebe --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c @@ -0,0 +1,126 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief This file provides functions to control the H bridge. + */ + +#include "mcs_assert.h" +#include "mcs_six_step.h" + +/* Mode for disabling or enabling software-based forced output */ +#define APT_PWM_MODE 0 +#define APT_FRC_MODE 1 + +#define PWM_SIGNAL 1 + +#define FRC_LOW APT_OUT_CTRL_ACTION_LOW +#define FRC_HIGH APT_OUT_CTRL_ACTION_HIGH + +/** + * @brief Force PWM output by APT + * @param APTx The APT to use + * @param PwmAout Force to be high or low + * @param PwmAenble PWMA signal software force mode + * @param PwmBout Force to be high or low + * @param PwmBenble PWMB signal software force mode + */ +static void APT_ForcePwmByApt(APT_RegStruct *aptx, APT_Act actMode) +{ + MCS_ASSERT_PARAM(aptx != NULL); + switch (actMode) { + case APT_CHA_PWM_CHB_LOW: + /* Channel A: 0 means not force output enable, channel A output PWM. */ + DCL_APT_DisableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + /* Channel B: 2 means channel B force output LOW due to the A_H_B_L invert. */ + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_HIGH: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 2 means channel B force output HIGH. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_LOW: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 1 means channel A force output HIGH due to the A_H_B_L invert. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_LOW); + break; + default: + break; + } +} + +/** + * @brief Output six-step square wave. + * @param handle The SixStepHandle. + * @retval None. + */ +void SixStepPwm(const SixStepHandle *handle) +{ + MCS_ASSERT_PARAM(handle != NULL); + APT_RegStruct *aptU = handle->controlApt.u->baseAddress; /* Get apt u\v\w baseaddress. */ + APT_RegStruct *aptV = handle->controlApt.v->baseAddress; + APT_RegStruct *aptW = handle->controlApt.w->baseAddress; + switch (handle->phaseStep) { + case STEP1: /* U+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP2: /* U+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP3: /* V+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP4: /* V+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP5: /* W+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + case STEP6: /* W+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h new file mode 100644 index 0000000000000000000000000000000000000000..08198c4caedc927239402496adfd0b3fb18df415 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h @@ -0,0 +1,79 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief The header file contains the following declaration: + * + StepEnum enum definition. + * + PhaseEnum enum definition. + * + UVW_AptReg structure definition. + * + SixStepHandle handle structure definition. + * + AptOutCombination structure definition. + * + Six Step Pwm Function And Six Step Pwm Overlap Function. + */ + +#ifndef MCS_SIX_STEP_H +#define MCS_SIX_STEP_H + +#include "apt.h" + +typedef enum { + STEP1 = 0, + STEP2, + STEP3, + STEP4, + STEP5, + STEP6, + STEP_MAX_NUM +} StepEnum; + +typedef enum { + U = 0, + V, + W, + PHASE_MAX_NUMS +} PhaseEnum; + +typedef enum { + APT_CHA_PWM_CHB_LOW, + APT_CHA_LOW_CHB_HIGH, + APT_CHA_LOW_CHB_LOW +} APT_Act; + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + APT_Handle *u; /**< Apt handle for controlling phase U. */ + APT_Handle *v; /**< Apt handle for controlling phase V. */ + APT_Handle *w; /**< Apt handle for controlling phase W. */ +} UVW_AptReg; + +typedef struct { + unsigned char phaseStep; /* Current step. */ + UVW_AptReg controlApt; /* Apt handles for controlling H bridge. */ +} SixStepHandle; + +typedef struct { + unsigned int upperout; /* High tube level */ + unsigned int upperstate; /* High tube state */ + unsigned int lowerout; /* Low tube level */ + unsigned int lowerstate; /* Low tube state */ +} AptOutCombination; + +void SixStepPwm(const SixStepHandle *handle); +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..d92ed312ac27deafb879eb892affc89d6cf35728 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/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 \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/readme.md b/vendor/yibaina_3061M/E7050_oled_ifd_sample/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..a1499e07293e8a3b78aa06e3963e806f914b5b33 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/readme.md @@ -0,0 +1,56 @@ +# E7050_oled_ifd_sample + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的红外控制E7050电机转动,OLED显示速度 + +**【环境要求】** + +- OLED使用IIC通信 +- 接线方式: + + ic0_SCL---GPIO4_5---J2_21 + + ic0_SDA---GPIO4_3---J2_26 + + 3.3v--3.3v + + GND--GND + +- VS1838红外接收模块 + +- 接线方式: + + S---GPIO2_2---J2_15 + + 3.3v ---J1_15 + + GND---J1_7 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 用配套的遥控发射红外或者用手机红外遥控发射对应码值。控制电机转动, + + + +KEY_OK = 28, 电机启动关闭 +KEY_UP =24, 调高速度 +KEY_DOWN = 82 调低速度 +KEY_LEFT = 8, +KEY_RIGHT =90, +KEY_1 = 69, 1档 +KEY_2 = 70, 2档 +KEY_3 = 71, 3档 +KEY_4 = 68, 4档 +KEY_5 = 64, 5档 +KEY_6 = 67, +KEY_7 = 7, +KEY_8 = 21, +KEY_9 =9, +KEY_0 = 25, +KEY_*=22 +KEY_# =13 diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/feature.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..13108bb335a3fe189a609d37b01dc36e0b3d37b8 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/feature.h @@ -0,0 +1,94 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +#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/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/main.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..3d2f9b3bb404d6d45bcb8d7b630b4f2625bf5abd --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/main.h @@ -0,0 +1,91 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +/* 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 "crg.h" +#include "iocmg.h" +#include "dma.h" +#include "dma_ex.h" +#include "i2c.h" +#include "i2c_ex.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 SYS_LED_PIN GPIO_PIN_3 +#define SYS_LED_HANDLE g_gpio2 +#define GpioStartStop_PIN GPIO_PIN_4 +#define GpioStartStop_HANDLE g_gpio2 + + +extern ACMP_Handle g_acmp0; +extern TIMER_Handle g_timer1; +extern TIMER_Handle g_timer2; +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 GPIO_Handle g_gpio1; +extern GPIO_Handle g_gpio2; +extern I2C_Handle g_i2c0; +extern DMA_Handle g_dmac; +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void MotorStatemachineCallBack(void *handle); +void TIMER1_DMAOverFlow_InterruptProcess(void *handle); +void MotorCarrierProcessCallback(void *aptHandle); +void MotorSysErrCallback(void *aptHandle); + +void MotorStartStopKeyCallback(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/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/system_init.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..1f0efc86c2bd184a17395ad474ef7d50af955e1e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/generatecode/system_init.c @@ -0,0 +1,680 @@ +/** + * @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. + * @date 2025-04-23 14:18:03 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_RATE 115200 + +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 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_ADCINA11; /* PIN9(ADC AIN11) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM5, &socParam); + + socParam.adcInput = ADC_CH_ADCINA12; /* PIN10(ADC AIN12) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM2, &socParam); + + socParam.adcInput = ADC_CH_ADCINA10; /* PIN8(ADC AIN10) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_5CLK; /* adc sample total time 5 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM9, &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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt0.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt0.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt0.adcTrg.cntCmpSOCA = 6000; /* 6000 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_CMPA_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_CMPC_UP; + 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, 6); /* 6 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt1.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt1.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt1.adcTrg.cntCmpSOCA = 1; /* 1 is count compare point of ADC trigger source SOCA when using CMPA */ + g_apt1.adcTrg.trgSrcSOCA = APT_CS_SRC_CNTR_ZERO; + g_apt1.adcTrg.trgScaleSOCA = 1; + + g_apt1.adcTrg.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt1.adcTrg.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + + 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt2.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 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); +} + +static void GPIO_Init(void) +{ + 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(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_LOW_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_FALL_EDGE); + + HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* gpio interrupt enable */ + + g_gpio2.pins = GPIO_PIN_2; + 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_NONE); + + return; +} + +__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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer1.bgLoad = (load < 1) ? 0 : (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, 2); /* 2 is priority value */ + IRQ_EnableN(IRQ_TIMER1); +} + + +__weak void TIMER2_InterruptProcess(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN TIMER2_InterruptProcess */ + /* USER CODE END TIMER2_InterruptProcess */ +} + +static void TIMER2_Init(void) +{ + HAL_CRG_IpEnableSet(TIMER2_BASE, IP_CLK_ENABLE); /* TIMER2 clock enable. */ + unsigned int load = ((float)HAL_CRG_GetIpFreq((void *)TIMER2) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 100; + + g_timer2.baseAddress = TIMER2; + g_timer2.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer2.bgLoad = (load < 1) ? 0 : (load - 1); /* Set timer value */ + g_timer2.mode = TIMER_MODE_RUN_PERIODIC; /* Run in period mode */ + g_timer2.prescaler = TIMERPRESCALER_NO_DIV; /* Don't frequency division */ + g_timer2.size = TIMER_SIZE_32BIT; /* 1 for 32bit, 0 for 16bit */ + g_timer2.interruptEn = BASE_CFG_ENABLE; + g_timer2.adcSocReqEnable = BASE_CFG_DISABLE; + g_timer2.dmaReqEnable = BASE_CFG_DISABLE; + HAL_TIMER_Init(&g_timer2); + IRQ_Register(IRQ_TIMER2, HAL_TIMER_IrqHandler, &g_timer2); + + HAL_TIMER_RegisterCallback(&g_timer2, TIMER_PERIOD_FIN, TIMER2_InterruptProcess); + IRQ_SetPriority(IRQ_TIMER2, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_TIMER2); +} + +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} +__weak void I2C0TxCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0TxCallback */ + /* USER CODE END I2C0TxCallback */ +} + +__weak void I2C0RxCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0RxCallback */ + /* USER CODE END I2C0RxCallback */ +} + +__weak void I2C0ErrorCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0ErrorCallback */ + /* USER CODE END I2C0ErrorCallback */ +} + +static void I2C0_Init(void) +{ + HAL_CRG_IpEnableSet(I2C0_BASE, IP_CLK_ENABLE); /* I2C0 clock enable. */ + g_i2c0.baseAddress = I2C0; + + g_i2c0.functionMode = I2C_MODE_SELECT_MASTER_ONLY; + g_i2c0.addrMode = I2C_7_BITS; + g_i2c0.sdaHoldTime = 10; /* 10 is sda Hold Time */ + g_i2c0.freq = 400000; /* freqence is 400000 */ + g_i2c0.transferBuff = NULL; + g_i2c0.ignoreAckFlag = BASE_CFG_DISABLE; + g_i2c0.handleEx.spikeFilterTime = 0; + g_i2c0.handleEx.sdaDelayTime = 0; + g_i2c0.timeout = 10000; /* 10000 is time out */ + g_i2c0.state = I2C_STATE_RESET; + g_i2c0.rxWaterMark = 1; /* 1 is Rx Threshold configuration */ + g_i2c0.txWaterMark = 12; /* 12 is Tx Threshold configuration */ + g_i2c0.dmaHandle = &g_dmac; + g_i2c0.txDmaCh = DMA_CHANNEL_ONE; + g_i2c0.rxDmaCh = DMA_CHANNEL_ZERO; + HAL_I2C_Init(&g_i2c0); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_MASTER_TX_COMPLETE_CB_ID, I2C0TxCallback); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_MASTER_RX_COMPLETE_CB_ID, I2C0RxCallback); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_ERROR_CB_ID, I2C0ErrorCallback); +} +static void DMA_Channel0Init(void *handle) +{ + DMA_ChannelParam dma_param; + dma_param.direction = DMA_PERIPH_TO_MEMORY_BY_DMAC; + dma_param.srcAddrInc = DMA_ADDR_UNALTERED; + dma_param.destAddrInc = DMA_ADDR_INCREASE; + dma_param.srcPeriph = DMA_REQUEST_I2C0_RX; + dma_param.destPeriph = DMA_REQUEST_MEM; + 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_Channel1Init(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_I2C0_TX; + dma_param.srcWidth = DMA_TRANSWIDTH_WORD; + dma_param.destWidth = DMA_TRANSWIDTH_WORD; + 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_ONE); +} + +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_i2c0)); + HAL_DMA_SetChannelPriorityEx(&g_dmac, DMA_CHANNEL_ZERO, DMA_PRIORITY_HIGHEST); + DMA_Channel1Init((void *)(&g_i2c0)); + HAL_DMA_SetChannelPriorityEx(&g_dmac, DMA_CHANNEL_ONE, DMA_PRIORITY_HIGHEST); +} +static void IOConfig(void) +{ + SYSCTRL0->SC_SYS_STAT.BIT.update_mode = 0; + SYSCTRL0->SC_SYS_STAT.BIT.update_mode_clear = 1; + /* Config PIN9 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_5_AS_ADC_AIN11); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_5_AS_ADC_AIN11, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_5_AS_ADC_AIN11, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_5_AS_ADC_AIN11, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_5_AS_ADC_AIN11, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN10 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_3_AS_ADC_AIN12); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_3_AS_ADC_AIN12, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_3_AS_ADC_AIN12, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_3_AS_ADC_AIN12, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_3_AS_ADC_AIN12, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN8 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_6_AS_ADC_AIN10); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_6_AS_ADC_AIN10, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_6_AS_ADC_AIN10, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_6_AS_ADC_AIN10, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_6_AS_ADC_AIN10, 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 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 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 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 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 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 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 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 */ + + /* Config PIN34 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_2_AS_GPIO2_2); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_2_AS_GPIO2_2, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_2_AS_GPIO2_2, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_2_AS_GPIO2_2, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_2_AS_GPIO2_2, DRIVER_RATE_2); /* Output signal edge fast/slow */ + + /* Config PIN15 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_5_AS_I2C0_SCL); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_5_AS_I2C0_SCL, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_5_AS_I2C0_SCL, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_5_AS_I2C0_SCL, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_5_AS_I2C0_SCL, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN16 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_3_AS_I2C0_SDA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_3_AS_I2C0_SDA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_3_AS_I2C0_SDA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_3_AS_I2C0_SDA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_3_AS_I2C0_SDA, 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(); + UART0_Init(); + ACMP0_Init(); + APT0_Init(); + APT1_Init(); + APT2_Init(); + ADC0_Init(); + TIMER1_Init(); + TIMER2_Init(); + DMA_Init(); + GPIO_Init(); + I2C0_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/yibaina_3061M/E7050_oled_ifd_sample/user/main.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..1d7563b902258e7993469bcb80f6c66a8bc83153 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/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. + * @date 2025-04-23 14:18:03 + */ + +#include "typedefs.h" +#include "feature.h" +#include "mcs_motor_process.h" +#include "main.h" +#include "ifd.h" +#include "oled.h" +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +ACMP_Handle g_acmp0; +TIMER_Handle g_timer1; +UART_Handle g_uart0; +APT_Handle g_apt0; +APT_Handle g_apt1; +APT_Handle g_apt2; +ADC_Handle g_adc0; +GPIO_Handle g_gpio1; +GPIO_Handle g_gpio2; +TIMER_Handle g_timer2; +I2C_Handle g_i2c0; +DMA_Handle g_dmac; +/* 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 diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.c new file mode 100644 index 0000000000000000000000000000000000000000..accec7f19eb979cb0d7c6203362b56ffe9e5a25c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.c @@ -0,0 +1,287 @@ +#include "ifd.h" +#include "debug.h" +#include "main.h" +#include "string.h" +#define RESET 0 +#define SET 1 + +#define IR_IN HAL_GPIO_GetPinValue(&g_gpio2, GPIO_PIN_2) // PA1 红外接收DQ引脚 +unsigned char ir_code[4]; // 解码值保存变量 +unsigned char ir_decode_ok_flag = RESET; // 解码成功标志位 +unsigned char key_data=0; + + +/* + NEC红外编码: 引导码 + 地址码 + 地址码(取反) + 数据 + 数据(取反) + 引导吗:0.56ms(低电平) + 2.25ms(高电平) + 数据1: 0.56ms(低电平) + 1.12ms(高电平) +*/ +// 红外解码程序,100us定期执行就可以,将该函数放在100us的定时器中即可。 + + + +void Ir_Decode(void) +{ + static unsigned int l_cnt = 0; // 低电平时间计数 + static unsigned int h_cnt = 0; // 高电平时间计数 + static unsigned int l_cnt_save = 0; // 保存低电平时长 + static unsigned int h_cnt_save = 0; // 保存高电平时长 + static unsigned char falling_edge_valid_flag = RESET; // IR电平由高变低标志位 + static unsigned char rcv_sync_ok_flag = RESET; // 同步码接收成功标志位 + static unsigned char bit_value = 0; // 位解码值 + static unsigned char bit_rcv_cnt = 0; // 位接收个数变量 + + + if( RESET == IR_IN ) + { + if( 0 == l_cnt ) // IR由高变低后立马记录上次测得的高电平时长 + { + h_cnt_save = h_cnt; + falling_edge_valid_flag = SET; + } + + + l_cnt ++; + if( l_cnt > 1600 ) // 防止计数溢出 + { + l_cnt = 1600; + } + h_cnt = 0; // 计数清零 + + } + else + { + if( 0 == h_cnt ) // IR由低变高后立马记录上次测得的低电平时长 + { + l_cnt_save = l_cnt; + } + + h_cnt ++; + if( h_cnt > 1600 ) // 防止计数溢出 + { + h_cnt = 1600; + } + + l_cnt = 0; // 计数清零 + + + if(ir_decode_ok_flag == 1) + { + if(h_cnt > 1200) + ir_decode_ok_flag = 2; // 短按 + } + + } + + + if( SET == falling_edge_valid_flag ) + { + falling_edge_valid_flag = RESET; + + /* 位解码 */ + if( ((l_cnt_save >= 3)&&(l_cnt_save <= 9)) && // 560us低电平, 560us高电平 + ((h_cnt_save >= 3)&&(h_cnt_save <= 9)) ) + { + bit_value = 0; + } + else if( ((l_cnt_save >= 3)&&(l_cnt_save <= 9)) && // 560us低电平,1680us高电平 + ((h_cnt_save >= 14)&&(h_cnt_save <= 20)) ) + { + bit_value = 1; + } + else + { + bit_value = 2; + } + + if( SET == rcv_sync_ok_flag ) + { + if((1 == bit_value) || (0 == bit_value) ) + { + if( bit_rcv_cnt < 8 ) + { + ir_code[0] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 16 ) + { + ir_code[1] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 24 ) + { + ir_code[2] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 32 ) + { + ir_code[3] |= (bit_value<< (bit_rcv_cnt%8)); + } + + if( bit_rcv_cnt >= 31 ) + { + ir_decode_ok_flag = SET; + rcv_sync_ok_flag = RESET; + } + + bit_rcv_cnt ++; + } + else + { + rcv_sync_ok_flag = RESET; // 位接收错误,重新解码 + } + } + + if( ((l_cnt_save >= 87)&&(l_cnt_save <= 93)) && + ((h_cnt_save >= 42)&&(h_cnt_save <= 48)) ) // 同步码,9ms低电平,4.5ms高电平 + { + rcv_sync_ok_flag = SET; + bit_rcv_cnt = 0; + ir_code[0] = 0; + ir_code[1] = 0; + ir_code[2] = 0; + ir_code[3] = 0; + } + else if(((l_cnt_save >= 87)&&(l_cnt_save <= 93)) && + ((h_cnt_save >= 20)&&(h_cnt_save <= 25)) ) + { + DBG_PRINTF("repeate code\r\n"); + ir_decode_ok_flag = 3; //长按 + } + + } +} + +//获取红外键值 +/* +KEY_OK = 28, +KEY_UP =24, +KEY_DOWN = 82 +KEY_LEFT = 8, +KEY_RIGHT =90, +KEY_1 = 69, +KEY_2 = 70, +KEY_3 = 71, +KEY_4 = 68, +KEY_5 = 64, +KEY_6 = 67, +KEY_7 = 7, +KEY_8 = 21, +KEY_9 =9, +KEY_0 = 25, +KEY_*=22 +KEY_# =13 +*/ + +unsigned char Remote_Scan(void) +{ + unsigned char key_value = 0; + + + // 校验地址码和命令码 + if((ir_code[0] == (unsigned char)~ir_code[1]) && + (ir_code[2] == (unsigned char)~ir_code[3])) + { + key_value = ir_code[2]; // 返回键值 + memset(ir_code, 0, sizeof(ir_code)); + } + + // switch(key_value) + // { + // case 69: + // DBG_PRINTF("1\r\n");//显示1 + // break; + + // case 70: + // DBG_PRINTF("2\r\n");//显示2 + // break; + + // case 71: + // DBG_PRINTF("3\r\n");//显示3 + // break; + + // case 68: + // DBG_PRINTF("4\r\n");//显示4 + // break; + + // case 64: + // DBG_PRINTF("5\r\n");//显示5 + // break; + + // case 67: + // DBG_PRINTF("6\r\n");//显示6 + // break; + + // case 7: + // DBG_PRINTF("7\r\n");//显示7 + // break; + + // case 21: + // DBG_PRINTF("8\r\n");//显示8 + // break; + + // case 9: + // DBG_PRINTF("9\r\n");//显示9 + // break; + + // case 25: + // DBG_PRINTF("0\r\n");//显示0 + // break; + + // case 22: + // DBG_PRINTF("*\r\n");//显示ASCII字符 + // break; + + // case 13: + // DBG_PRINTF("#\r\n");//显示ASCII字符 + // break; + + // case 24: + + // DBG_PRINTF("UP\r\n");//显示ASCII字符 + // break; + + // case 8: + // DBG_PRINTF("LEFT\r\n");//显示ASCII字符 + // break; + + // case 82: + + // DBG_PRINTF("DOWN\r\n");//显示ASCII字符 + + // break; + + // case 90: + // DBG_PRINTF("RIGHT\r\n");//显示ASCII字符 + // break; + + // case 28: + // DBG_PRINTF("OK\r\n"); + // break; + + // default: + + // break; + // } + + + return key_value; +} + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.h new file mode 100644 index 0000000000000000000000000000000000000000..6559a3bf53e7594cbd963e03ac48bc671fac326e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/IR/ifd.h @@ -0,0 +1,36 @@ +#ifndef __IR_H +#define __IR_H + + + +extern unsigned char ir_code[4]; +extern unsigned char key_data; +void Ir_Decode(void); + +unsigned char Remote_Scan(void); + + + + + + + + + + + + + + + + +#endif + + + + + + + + + diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..4fd139fc8a9c3aea075ed467b4fbff9845d1c494 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c @@ -0,0 +1,781 @@ +/** + * @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 for ECBMCU201MPC board. + * @details BLDC six-step application based on the ECBMCU201MPC board + * 1) Motor model is Gimbal GBM2804H-100T. + * 2) Select the bldc six-step sensorless example in the sample column + of chipConfig and click Generate Code. + * 3) It's power supply must be changed to 12V. + */ + +#include "debug.h" +#include "mcs_assert.h" +#include "mcs_user_config.h" +#include "mcs_status.h" +#include "mcs_carrier.h" +#include "mcs_motor_process.h" +#include "ifd.h" +#include "oled.h" +/*------------------------------- Macro Definition -----------------------------------------------*/ +#define US_PER_MS 1000 +#define APT_FULL_DUTY 1.0f + +/* Motor control handle for bldc */ +static MtrCtrlHandle g_mc; + +static APT_RegStruct* g_aptCp[PHASE_MAX_NUM] = {BRIDGE_CTR_APT_U, BRIDGE_CTR_APT_V, BRIDGE_CTR_APT_W}; + +static oled_display_flag=0; + +/** + * @brief Initialzer of system tick. + * @param mtrCtrl Motor control struct handle. + * @retval None. + */ +static void TimerTickInit(MtrCtrlHandle *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 Read the ADC current sampling value of the compressor. + * @param CurrUvw Three-phase current. + * @retval None. + */ +static void ReadBemfUVWMotor(UVWBemf *bemfUVW) +{ + MCS_ASSERT_PARAM(bemfUVW != NULL); + bemfUVW->u = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_U_SOC_NUM)&0xFFF); + bemfUVW->v = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_V_SOC_NUM)&0xFFF); + bemfUVW->w = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_W_SOC_NUM)&0xFFF); +} + +/** + * @brief Init motor control task. + * @retval None. + */ +static void TSK_InitMotor(void) +{ + /* Initialize target speed. */ + g_mc.spdCmdHz = SDP_TARGET_VALUE; + /* zeroPoint = IN_VOLTAGE_BUS / 2.0; 4095/3.3 :ADC value corresponding to 1 V */ + g_mc.zeroPoint = ((((float)IN_VOLTAGE_BUS / 2.0) * VOL_DIVIDER_COEFFICIENT) * 4095 / 3.3); + g_mc.pwmDuty = FORCE_DRAG_MINDUTY; + + /* Sets the number of sample filtering times for zero-crossing sampling. */ + g_mc.sysVar.bemfFilterCnt = FILTER_COUNT; + g_mc.sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + + g_mc.stateMachine = FSM_IDLE; + g_mc.aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Speed management initialization. */ + RMG_Init(&g_mc.spdRmg, CTRL_SYSTICK_PERIOD, USER_SPD_SLOPE); /* Init speed slope */ + TimerTickInit(&g_mc); + + /* Pid control parameter initialization. */ + g_mc.spdPi.kp = SPD_PID_KP; + g_mc.spdPi.ki = SPD_PID_KI; + g_mc.spdPi.ts = SPD_PID_TS; + g_mc.spdPi.upperLimit = APT_DUTYLIMIT_MAX; + g_mc.spdPi.lowerLimit = APT_DUTYLIMIT_MIN; + + /* BLDC six-step control initialization. */ + g_mc.stepCtrl.phaseStep = STEP1; + g_mc.stepCtrl.controlApt.u = &g_apt0; + g_mc.stepCtrl.controlApt.v = &g_apt1; + g_mc.stepCtrl.controlApt.w = &g_apt2; +} + + +/** + * @brief Software Initialization. + * @retval None. + */ +static void InitSoftware(void) +{ + TSK_InitMotor(); + + g_mc.readBemfUVW = ReadBemfUVWMotor; +} + +/** + * @brief Enable three-phase pwm output. + * @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 = 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 = 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 强制转子对准原位。 + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceAlign(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + MotorPwmOutputEnable(g_aptCp); + mtrCtrl->stepCtrl.phaseStep = STEP6; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->stepCtrl.phaseStep = STEP1; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); +} + +/** + * @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_WAIT_STOP; + } +} + +/** + * @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 int maxDutyCnt) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + MCS_ASSERT_PARAM(maxDutyCnt != 0); + unsigned int dutyCnt; + dutyCnt = maxDutyCnt * APT_FULL_DUTY; + /* Open the three-phase lower pipe */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = aptAddr[i]; + aptx->TC_REFC.BIT.rg_cnt_refc = dutyCnt; + aptx->TC_REFD.BIT.rg_cnt_refd = dutyCnt; + } +} + +/** + * @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(MtrCtrlHandle *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 Clear historical values of all controller before start-up. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ClearBeforeStartup(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Clear bemf parameters. */ + mtrCtrl->bemf.u = 0; + mtrCtrl->bemf.v = 0; + mtrCtrl->bemf.w = 0; + + /* Clear tickcnt. */ + mtrCtrl->msTickCnt = 0; + + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + + /* Clear spd parameters. */ + mtrCtrl->spdEstHz = 0; + mtrCtrl->spdRefHz = 0; + + mtrCtrl->stepCtrl.phaseStep = STEP1; + + mtrCtrl->sysTickCnt = 0; + + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + mtrCtrl->sysVar.changePhaseFlag = 0; + mtrCtrl->sysVar.firstEventFilterFlag = 0; + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 0; + for (int i = 0; i < STEP_MAX_NUM; i++) { + mtrCtrl->sysVar.stepTime[i] = 0; + } + /* RMG CLEAR */ + RMG_Clear(&mtrCtrl->spdRmg); /* Clear the history value of speed slope control */ + /* SPDCTRL CLEAR */ + PID_Clear(&mtrCtrl->spdPi); +} + +/** + * @brief Check bootstrap capacitor charge time. + * @param mtrCtrl The motor control handle. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckBootstrpCapChargeTime(MtrCtrlHandle *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) { + /* Update Status. */ + *stateMachine = FSM_CLEAR; + } +} + +/** + * @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 Deceleration control phase before stop. + * @param mtrCtrl The motor control handle. + * @param statusReg Motor Control Status. + * @param targetSpd Deceleration target value. + * @param switchSpd Switch to stop state speed. + * @retval None. + */ +static void DecelerateSpeed(MtrCtrlHandle *mtrCtrl, FsmState *stateMachine, float targetSpd, float switchSpd) +{ + /* Reduce speed before stop. */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, targetSpd); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + if (mtrCtrl->spdRefHz <= switchSpd) { /* Maximum speed for switching to the FSM_STOP state */ + *stateMachine = FSM_STOP; + } +} + +/** + * @brief System timer tick task. + * @param mtrCtrl The motor control handle. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void TSK_SystickIsr(MtrCtrlHandle *mtrCtrl, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + SysStatusReg *statusReg = &mtrCtrl->statusReg; + volatile FsmState *stateMachine = &mtrCtrl->stateMachine; + mtrCtrl->msTickCnt++; + /* Pre-processing of motor status. */ + MotorStatePerProc(statusReg, stateMachine); + /* statemachine */ + switch (*stateMachine) { + case FSM_IDLE: + CheckSysCmdStart(mtrCtrl, aptAddr, statusReg, (FsmState *)stateMachine); + break; + case FSM_CAP_CHARGE: + /* Bootstrap Capacitor Charging Timing */ + CheckBootstrpCapChargeTime(mtrCtrl, (FsmState *)stateMachine); + break; + case FSM_CLEAR: + /* Clearing control parameters. */ + ClearBeforeStartup(mtrCtrl); + /* Rotor alignment. */ + ForceAlign(mtrCtrl); + *stateMachine = FSM_STARTUP; + break; + case FSM_STARTUP: + /* Forced drag. */ + break; + case FSM_RUN: + /* Speed ramp control */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + break; + case FSM_WAIT_STOP: + /* 5.0f : maximum speed for switching to the FSM_STOP state */ + DecelerateSpeed(mtrCtrl, (FsmState *)stateMachine, 0.0f, 5.0f); + break; + case FSM_STOP: + MotorPwmOutputDisable(aptAddr); + SysRunningClr(statusReg); + *stateMachine = FSM_IDLE; + break; + case FSM_FAULT: + /* Overcurrent state */ + CheckOverCurrentState(statusReg, (FsmState *)stateMachine); + break; + default: + break; + } +} + +/** + * @brief Overcurrent protection. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorSysErrCallback(void *aptHandle) +{ + /* Overcurrent protection callback function. */ + BASE_FUNC_UNUSED(aptHandle); + MotorPwmOutputDisable(g_aptCp); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_U], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_V], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_W], APT_OC_COMBINE_EVENT_A1); + /* Status setting error */ + SysErrorSet(&g_mc.statusReg); + DBG_PRINTF("APT error! \r\n"); + HAL_GPIO_SetValue(&g_gpio2, GPIO_PIN_3, GPIO_LOW_LEVEL); +} + +/** + * @brief Motor blockage protection function. + * @retval None. + */ +static void MotorBlockageProtect(void) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= g_mc.sysVar.lastZeroPoint) + ? currentTick - g_mc.sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - g_mc.sysVar.lastZeroPoint + currentTick + 1; + if (intervalTick > SYSTICK_GetCRGHZ()) { + MotorPwmOutputDisable(g_aptCp); + SysErrorSet(&g_mc.statusReg); + g_mc.spdEstHz = 0; + return; + } +} + +/** + * @brief Carrier Interruption. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorCarrierProcessCallback(void *aptHandle) +{ + BASE_FUNC_UNUSED(aptHandle); + /* USER CODE BEGIN APT0_TIMER_INTERRUPT */ + MCS_CarrierProcess(&g_mc); + if (g_mc.stateMachine == FSM_RUN || g_mc.stateMachine == FSM_WAIT_STOP) { + MotorBlockageProtect(); + } + /* USER CODE END APT0_TIMER_INTERRUPT */ +} + +/** + * @brief Change phase delay callback function. + * @param handle The TIMER1 Handle. + * @retval None. + */ +void MotorStatemachineCallBack(void *handle) +{ + /* TIMER1CallbackFunction */ + BASE_FUNC_UNUSED(handle); + TSK_SystickIsr(&g_mc, g_aptCp); +} + +/** + * @brief 显数据 + * @param None + * @retval + */ +void DispSomething(void) +{ + + switch(oled_display_flag) + { + case 1: + + OLED_displaystr(0,0,"档位:1"); + oled_display_flag=0; + break; + + case 2: + + OLED_displaystr(0,0,"档位:2"); + oled_display_flag=0; + break; + + case 3: + + + OLED_displaystr(0,0,"档位:3"); + oled_display_flag=0; + break; + + case 4: + + + OLED_displaystr(0,0,"档位:4"); + oled_display_flag=0; + break; + + case 5: + + OLED_displaystr(0,0,"档位:5"); + oled_display_flag=0; + + break; + case 6: + + g_mc.spdEstHz=0; + + break; + default: + + break; + + } + + OLED_ShowNum(2,6,g_mc.spdEstHz*60/POLES,3,16);//显示速度 +} + +/** + * @brief 100us解码红外模块 + * @param None. + * @retval None. + */ + +void TIMER2_InterruptProcess(void *handle) +{ + BASE_FUNC_UNUSED(handle); + + static float spdCmdHz = 0; + static float spdCmdHzLast = SDP_MAX_VALUE; + + Ir_Decode();//解码 + key_data=Remote_Scan(); + + switch(key_data) + { + case 69: + spdCmdHz=15;//显示1 + DBG_PRINTF("1\r\n");//显示1 + + oled_display_flag=1; + break; + + case 70: + spdCmdHz=25;//显示2 + DBG_PRINTF("2\r\n"); + oled_display_flag=2; + break; + + case 71: + spdCmdHz=35;//显示3 + DBG_PRINTF("3\r\n"); + oled_display_flag=3; + break; + + case 68: + spdCmdHz=45;;//显示4 + DBG_PRINTF("4\r\n"); + oled_display_flag=4; + break; + + case 64: + spdCmdHz=55;;//显示5 + DBG_PRINTF("5\r\n"); + oled_display_flag=5; + + break; + + case 67: + DBG_PRINTF("6\r\n");//显示6 + break; + + case 7: + DBG_PRINTF("7\r\n");//显示7 + break; + + case 21: + DBG_PRINTF("8\r\n");//显示8 + break; + + case 9: + DBG_PRINTF("9\r\n");//显示9 + break; + + case 25: + DBG_PRINTF("0\r\n");//显示0 + break; + + case 22: + DBG_PRINTF("*\r\n");//显示ASCII字符 + break; + + case 13: + DBG_PRINTF("#\r\n");//显示ASCII字符 + break; + + case 24: + spdCmdHz+=5; + DBG_PRINTF("UP\r\n");//显示ASCII字符 + break; + + case 8: + + DBG_PRINTF("LEFT\r\n");//显示ASCII字符 + break; + + case 82: + spdCmdHz-=5; + DBG_PRINTF("DOWN\r\n");//显示ASCII字符 + + break; + + case 90: + DBG_PRINTF("RIGHT\r\n");//显示ASCII字符 + break; + + case 28: //OK + if (SysIsRunning(&g_mc.statusReg)) { /* stop apt output, motor is off status */ + SysCmdStopSet(&g_mc.statusReg); + oled_display_flag=6; + } else { /* start apt output, motor is on status */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + SysCmdStartSet(&g_mc.statusReg); + oled_display_flag=0; + } + + + DBG_PRINTF("OK\r\n"); + break; + + default: + + break; + + + // OLED_ShowNum(2,6,g_mc.spdEstHz,3,16); + } + + + + if (spdCmdHz < SDP_MIN_VALUE) { /* Speed protection. */ + spdCmdHz = SDP_MIN_VALUE; + } + if (spdCmdHz > SDP_MAX_VALUE) { + spdCmdHz = SDP_MAX_VALUE; + } + float delta = spdCmdHzLast > spdCmdHz ? (spdCmdHzLast - spdCmdHz) : (spdCmdHz - spdCmdHzLast); + /* 1.0 : If the speed fluctuation is less than 1.0Hz, no change is made. */ + if (delta < 1.0) { + return; + } + spdCmdHzLast = spdCmdHz; + g_mc.spdCmdHz = spdCmdHz; + + + +} + + +/** + * @brief Check Potentiometer Value and adjust speed. + * @param None. + * @retval None. + */ +static void AdjustSpeedFunction(void) +{ + static unsigned int potentiomitorAdcValue = 0; + static float spdCmdHz = 0; + static float spdCmdHzLast = SDP_MAX_VALUE; + HAL_ADC_SoftTrigSample(&ADC_HANDLE, ADC_SOC_NUM9); /* Get the speed adjustment resistance. */ + potentiomitorAdcValue = HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_SOC_NUM9); + + + /* 4045.0 is adc sample max value of potentiomitor */ + spdCmdHz = (float)potentiomitorAdcValue / 4045.0 * SDP_MAX_VALUE; + + if (spdCmdHz < SDP_MIN_VALUE) { /* Speed protection. */ + spdCmdHz = SDP_MIN_VALUE; + } + if (spdCmdHz > SDP_MAX_VALUE) { + spdCmdHz = SDP_MAX_VALUE; + } + float delta = spdCmdHzLast > spdCmdHz ? (spdCmdHzLast - spdCmdHz) : (spdCmdHz - spdCmdHzLast); + /* 1.0 : If the speed fluctuation is less than 1.0Hz, no change is made. */ + if (delta < 1.0) { + return; + } + spdCmdHzLast = spdCmdHz; + g_mc.spdCmdHz = spdCmdHz; +} + +/** + * @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 (SysIsRunning(&g_mc.statusReg)) { /* stop apt output, motor is off status */ + SysCmdStopSet(&g_mc.statusReg); + } else { /* start apt output, motor is on status */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + SysCmdStartSet(&g_mc.statusReg); + } + } +} + +/** + * @brief User application entry. + * @retval BSP_OK. + */ +int MotorMainProcess(void) +{ + SystemInit(); + OLED_Init(); + /* System Initialization. */ + unsigned int tickNum100Ms = 200; /* 100ms tick */ + static unsigned int tickCnt100Ms = 0; + unsigned int tickNum500Ms = 1000; /* 500ms tick */ + static unsigned int tickCnt500Ms = 0; + + HAL_TIMER_Start(&g_timer1); + HAL_TIMER_Start(&g_timer2); + /* Disable PWM output before startup. */ + MotorPwmOutputDisable(g_aptCp); + InitSoftware(); + /* Start the PWM clock. */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + + OLED_displaystr(0,0,"档位:1"); + OLED_displaystr(0,3,"电机速度:"); + OLED_displaystr(64,6,"RPM"); + + + while (true) { + if (g_mc.msTickCnt - tickCnt100Ms >= tickNum100Ms) { + tickCnt100Ms = g_mc.msTickCnt; + /* User Code 100ms Event */ + AdjustSpeedFunction(); + + } + if (g_mc.msTickCnt - tickCnt500Ms >= tickNum500Ms) { + if (SysIsError(&g_mc.statusReg) == true) { + break; + } + /* The LED blinks when no status is not error. */ + HAL_GPIO_TogglePin(&SYS_LED_HANDLE, SYS_LED_PIN); + + tickCnt500Ms = g_mc.msTickCnt; + + DispSomething();//显示OLED数据 + + + } + + + + } + return 0; +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..a2fdeb2c62a9185aa9d9d08c3408e0e88486066c --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h @@ -0,0 +1,47 @@ +/** + * @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 ECBMCU201MPC board. + */ +#ifndef McuMagicTag_MCS_MOTOR_PROCESS_H +#define McuMagicTag_MCS_MOTOR_PROCESS_H + +#include "main.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/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..f193532a63ce3d468aaac9e35791912761e5d47e --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h @@ -0,0 +1,94 @@ +/** + * @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_config.h + * @author MCU Algorithm Team + * @brief This file provides config macros for ECBMCU201MPC app. + */ +#ifndef McuMagicTag_MCS_CONFIG_H +#define McuMagicTag_MCS_CONFIG_H + +#if defined(CHIP_3061MNPICA) || defined(CHIP_3061MNNICA) || defined(CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) +#define ADC_U_SOC_NUM ADC_SOC_NUM2 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM6 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 +#define ADC_HANDLE g_adc0 +#endif + +#if defined (CHIP_3066MNPIRH) || defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) +#define ADC_U_SOC_NUM ADC_SOC_NUM3 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM7 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 + +#define ADC_HANDLE g_adc2 +#endif + +#define APT_PWM_FREQ 12000 /* PWM frequency 12K Hz. */ +#define CTRL_CURR_PERIOD (1.0f / APT_PWM_FREQ) /* carrier ISR period (S) */ +#define CTRL_CURE_PERIOD_US 83 + +#define SYSTICK_PERIOD_US 500u /* systick period. unit : us */ + +#define INV_CAP_CHARGE_MS 3u /* Bootstrap capacitor charge time. unit : ms */ + +#define CTRL_SYSTICK_PERIOD 0.0005f /* systick control period, 500us */ + +#define USER_SPD_SLOPE 60.0f /* slope of velocity change */ + +#define IN_VOLTAGE_BUS 24 /* Motor input voltage */ +#define POLES 14 /* 电机磁极对数 */ +#define MATH_PI 3.14 /* Pi */ +#define MOTOR_K 1.62 /* 转矩系数 */ + +#define RAMP_STP 60 /* Slope of forced draging acceleration */ +#define RAMP_DUTY_PWM 0.5 /* 1.0% */ + +#define FORCE_DRAG_MINDUTY 15 /* APT minimum duty cycle during forced drag */ +#define FORCE_DRAG_MAXDUTY 20 /* APT maximum duty cycle during forced drag */ + +#define DRAG_START_INTERVAL 1000 /* Force drag change phase time */ +#define DRAG_STOP_INTERVAL 400 /* Force drag change phase time */ + +/* Parameters of the motor in the RUN */ +#define FILTER_COUNT 3 /* Filter Times */ +#define PHASE_OFFSET 9000 /* Phase delay due to filtering */ + +#define APT_DUTYLIMIT_MAX 99.9 /* 输出APT的最大占空比 */ +#define APT_DUTYLIMIT_MIN 8.0 /* Minimum duty cycle of the output APT */ + +#define BRIDGE_CTR_APT_U APT0 /* APT address that controls the U phase */ +#define BRIDGE_CTR_APT_V APT1 /* APT address that controls the V phase */ +#define BRIDGE_CTR_APT_W APT2 /* APT address that controls the W phase */ + +#define SDP_MAX_VALUE 58.8 /* 最大相位变化频率 */ +#define SDP_MIN_VALUE 15.0 /* Minimum change phase frequency */ +#define SDP_TARGET_VALUE 58.8 /* 目标相位变化频率 */ + +/* SPD PID Param */ +#define SPD_PID_KP 0.9 /* P parameter of PID control */ +#define SPD_PID_KI 40 /* I parameter of PID control */ +#define SPD_PID_TS 0.0005 /* TS parameter of PID control cycle */ + +#define OP_TO_CL_INTERGRAL 8.0 /* Open-loop switching closed-loop integral term to prevent sudden current change. */ + +#define VOL_DIVIDER_COEFFICIENT 0.09091f /* Division coefficient of the zero-crossing detection sampling circuit */ + +#define SPD_FILTER_FC 30 + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..7779fbef2e3eee99fb209f617bb4d3f7d923309d --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c @@ -0,0 +1,224 @@ +/** + * @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_user_config.h" +#include "mcs_assert.h" +#include "debug.h" + +#define S_TO_US 1000000 +#define S_TO_SYSTICK 100000000 + +/** + * @brief Sets the duty cycle of the H-bridge APT. + * @param aptHandle APT module handle. + * @param duty PWM duty. Range: 0.1 ~ 99.9. + * @retval None. + */ +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(duty > 0); + /* Set pwm duty of uvw pahse */ + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.u, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.v, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.w, duty); +} + +/** + * @brief Strong drag start. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceDragAcc(MtrCtrlHandle *mtrCtrl) +{ + /* Verifying Parameters. */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + unsigned int voltageDValue; + unsigned int dragChangeFreq; + unsigned int timerperiod; + unsigned int freqLast; + unsigned int aptCountsOneUs; + + mtrCtrl->sysVar.accTimeCnt++; + if (mtrCtrl->sysVar.accTimeCnt < mtrCtrl->sysVar.dragChangePhaseTime) { + return; + } + + mtrCtrl->sysVar.accTimeCnt = 0; + /* Step 1: Calculate the voltage difference. */ + voltageDValue = IN_VOLTAGE_BUS * RAMP_DUTY_PWM; + /* Step 2: Calculate the commutation frequency. */ + freqLast = S_TO_US / (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US); + dragChangeFreq = voltageDValue * STEP_MAX_NUM * POLES / (MOTOR_K * 2 * MATH_PI) + freqLast; /* 2*PI = 360° */ + /* Step 3: Convert the commutation frequency to the commutation count value. */ + timerperiod = mtrCtrl->stepCtrl.controlApt.u->waveform.timerPeriod * CTRL_CURE_PERIOD_US; + mtrCtrl->sysVar.dragChangePhaseTime = S_TO_US / (timerperiod * dragChangeFreq); + + /* Determine whether the change phase speed has reached the speed of stopping forced drag. */ + if (mtrCtrl->sysVar.dragChangePhaseTime < DRAG_STOP_INTERVAL) { + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_STOP_INTERVAL; + mtrCtrl->sysVar.accTimeCnt = 0; + mtrCtrl->sysVar.bemfFilterCnt = 0; + mtrCtrl->stateMachine = FSM_RUN; + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); + mtrCtrl->spdPi.integral = OP_TO_CL_INTERGRAL; + } + + /* Shorten the time interval of forced drag change phase. */ + mtrCtrl->pwmDuty += RAMP_DUTY_PWM; + aptCountsOneUs = HAL_CRG_GetIpFreq(APT0_BASE) / S_TO_US; + mtrCtrl->sysVar.waitTime = (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US * aptCountsOneUs) >> 1; + /* Change phase time is 2 the waiting time. */ + mtrCtrl->spdRefHz = (float)(HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime * 2)) / STEP_MAX_NUM; + mtrCtrl->spdEstHz = mtrCtrl->spdRefHz; + mtrCtrl->spdRmg.yLast = mtrCtrl->spdRefHz; + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + /* Limiting the PWM Duty Cycle Range. */ + if (mtrCtrl->pwmDuty > FORCE_DRAG_MAXDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MAXDUTY; + } + if (mtrCtrl->pwmDuty < FORCE_DRAG_MINDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + } + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); +} + +/** + * @brief Zero-crossing filter. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroSampleFilter(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->sysVar.bemfFilterCnt++; + /* Filter the number of samples. */ + if (mtrCtrl->sysVar.bemfFilterCnt >= FILTER_COUNT) { + mtrCtrl->sysVar.bemfFilterCnt = 0; + unsigned int currentTick = DCL_SYSTICK_GetTick(); + if (mtrCtrl->sysVar.firstEventFilterFlag == 0) { + mtrCtrl->sysVar.lastZeroPoint = currentTick; + mtrCtrl->sysVar.changePhaseFlag = 1; + mtrCtrl->sysVar.firstEventFilterFlag = 1; + return; + } + /* Calculate the time interval between the last zero crossing. */ + mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] = currentTick >= mtrCtrl->sysVar.lastZeroPoint + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + mtrCtrl->sysVar.stepTimeNum++; + /* Wait time is half the interval. */ + mtrCtrl->sysVar.waitTime = mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] >> 1; + mtrCtrl->sysVar.waitTime -= PHASE_OFFSET; + mtrCtrl->sysVar.lastZeroPoint = currentTick; + /* Update flag. */ + mtrCtrl->sysVar.changePhaseFlag = 1; + } +} + +/** + * @brief Back EMF zero crossing check. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroCheck(MtrCtrlHandle *mtrCtrl) +{ + /* The step corresponds to different conditional judgments. */ + unsigned int bemfCheckTable[STEP_MAX_NUM] = {mtrCtrl->bemf.w < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.w > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u > mtrCtrl->zeroPoint ? 1 : 0}; + + if (bemfCheckTable[mtrCtrl->stepCtrl.phaseStep] == 1) { + BemfZeroSampleFilter(mtrCtrl); + } +} + +/** + * @brief Change phase and speed estimation. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ChangePhase(MtrCtrlHandle *mtrCtrl) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= mtrCtrl->sysVar.lastZeroPoint) + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + /* Start average filtering when the number of recorded data reaches six. */ + if (mtrCtrl->sysVar.stepTimeNum >= STEP_MAX_NUM) { + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 1; + } + /* If the accumulated time is greater than the waiting commutation time, commutation is performed. */ + if (intervalTick > mtrCtrl->sysVar.waitTime) { + if (mtrCtrl->sysVar.stepTimeFilterEnable) { /* 6-step commutation time averaging if filtering is enabled. */ + unsigned int totalTime = mtrCtrl->sysVar.stepTime[STEP1] + mtrCtrl->sysVar.stepTime[STEP2] + + mtrCtrl->sysVar.stepTime[STEP3] + mtrCtrl->sysVar.stepTime[STEP4] + + mtrCtrl->sysVar.stepTime[STEP5] + mtrCtrl->sysVar.stepTime[STEP6]; + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / totalTime; + } else { + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime << 1) / STEP_MAX_NUM; + } + /* Change phase. */ + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + mtrCtrl->sysVar.changePhaseFlag = 0; + } +} + +/** + * @brief Zero-crossing detection and change phase + * @param mtrCtrl The motor control handle. + * @retval None. + */ +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + /* Offset value of the calibration value of the three-phase current */ + + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + ForceDragAcc(mtrCtrl); /* Forced drag. */ + break; + + case FSM_RUN: + case FSM_WAIT_STOP: + mtrCtrl->readBemfUVW(&mtrCtrl->bemf); + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + if (mtrCtrl->sysVar.changePhaseFlag) { + /* Change phase process. */ + ChangePhase(mtrCtrl); + } else { + /* Zero-crossing detection procedure. */ + BemfZeroCheck(mtrCtrl); + } + break; + + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..05fc26667e96b59288aba49344f448a3bf243816 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h @@ -0,0 +1,91 @@ +/** + * @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_six_step.h" +#include "mcs_ramp_mgmt.h" +#include "mcs_spd_ctrl.h" +#include "mcs_fsm.h" + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + unsigned int u; /**< Component u of the three-phase static coordinate frame variable. */ + unsigned int v; /**< Component v of the three-phase static coordinate frame variable. */ + unsigned int w; /**< Component w of the three-phase static coordinate frame variable. */ +} UVWBemf; + +typedef void (*ReadBemf)(UVWBemf *bemfUVW); + +/** + * @brief The definition of the systematic global variables + */ +typedef struct { + unsigned char changePhaseFlag; /**< Flag indicating that delay change phase is required */ + unsigned char firstEventFilterFlag; /**< First zero-crossing event filtering flag. */ + unsigned int dragChangePhaseTime; /**< Interval for forced drag acceleration */ + unsigned int accTimeCnt; /**< Acceleration time count */ + + unsigned int bemfFilterCnt; /**< Number of sample filtering times for zero-crossing detection. */ + + unsigned int lastZeroPoint; /**< Time of the last zero point */ + unsigned int waitTime; /**< Time to wait for change phase */ + unsigned int stepTime[STEP_MAX_NUM]; /**< Record the time spent on each step */ + unsigned int stepTimeNum; /**< Number of data records in the steptime array. */ + unsigned int stepTimeFilterEnable; +} SysVariable; + +typedef struct { + volatile float spdCmdHz; /**< Set target change phase frequency */ + float spdRefHz; /**< Command values after speed ramp management */ + float spdEstHz; /**< Actual change phase frequency of feedback */ + float pwmDuty; /**< APT duty cycle */ + unsigned int zeroPoint; /**< Adc value of zero point */ + + unsigned short aptMaxcntCmp; /**< Apt Maximum Comparison Count */ + + unsigned short sysTickCnt; /**< System Timer Tick Count */ + unsigned short capChargeTickNum; /**< Bootstrap Capacitor Charge Tick Count */ + unsigned short msTickNum; /**< Number of ticks corresponding to 1 ms */ + volatile unsigned int msTickCnt; /**< Millisecond-level counter, which can be used in 1-ms and 5-ms tasks. */ + + RMG_Handle spdRmg; /**< Ramp management struct for the speed controller input reference */ + PID_Handle spdPi; /**< PI controller struct in the speed controller. */ + + UVWBemf bemf; /**< Three-phase back electromotive force */ + SixStepHandle stepCtrl; /**< Control structure of six-step square wave */ + + SysVariable sysVar; /**< System Variables */ + SysStatusReg statusReg; /**< System Status */ + FsmState stateMachine; /**< BLDC Motor Control State Machine */ + + ReadBemf readBemfUVW; /**< Function interface for obtaining the three-phase electromotive force */ +} MtrCtrlHandle; + +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl); + +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h new file mode 100644 index 0000000000000000000000000000000000000000..b3c79ea2c8fccfc6f797d664899b8a249118aa3d --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h @@ -0,0 +1,55 @@ +/** + * @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_fsm.h + * @author MCU Algorithm Team + * @brief This file provides the definition of finite statemachine (FSM). + */ + +#ifndef McuMagicTag_MCS_FSM_H +#define McuMagicTag_MCS_FSM_H + +/** + * @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; + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c new file mode 100644 index 0000000000000000000000000000000000000000..c86e609c8e3512ec0e0569c06aae5f38afff8ebe --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c @@ -0,0 +1,126 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief This file provides functions to control the H bridge. + */ + +#include "mcs_assert.h" +#include "mcs_six_step.h" + +/* Mode for disabling or enabling software-based forced output */ +#define APT_PWM_MODE 0 +#define APT_FRC_MODE 1 + +#define PWM_SIGNAL 1 + +#define FRC_LOW APT_OUT_CTRL_ACTION_LOW +#define FRC_HIGH APT_OUT_CTRL_ACTION_HIGH + +/** + * @brief Force PWM output by APT + * @param APTx The APT to use + * @param PwmAout Force to be high or low + * @param PwmAenble PWMA signal software force mode + * @param PwmBout Force to be high or low + * @param PwmBenble PWMB signal software force mode + */ +static void APT_ForcePwmByApt(APT_RegStruct *aptx, APT_Act actMode) +{ + MCS_ASSERT_PARAM(aptx != NULL); + switch (actMode) { + case APT_CHA_PWM_CHB_LOW: + /* Channel A: 0 means not force output enable, channel A output PWM. */ + DCL_APT_DisableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + /* Channel B: 2 means channel B force output LOW due to the A_H_B_L invert. */ + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_HIGH: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 2 means channel B force output HIGH. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_LOW: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 1 means channel A force output HIGH due to the A_H_B_L invert. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_LOW); + break; + default: + break; + } +} + +/** + * @brief Output six-step square wave. + * @param handle The SixStepHandle. + * @retval None. + */ +void SixStepPwm(const SixStepHandle *handle) +{ + MCS_ASSERT_PARAM(handle != NULL); + APT_RegStruct *aptU = handle->controlApt.u->baseAddress; /* Get apt u\v\w baseaddress. */ + APT_RegStruct *aptV = handle->controlApt.v->baseAddress; + APT_RegStruct *aptW = handle->controlApt.w->baseAddress; + switch (handle->phaseStep) { + case STEP1: /* U+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP2: /* U+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP3: /* V+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP4: /* V+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP5: /* W+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + case STEP6: /* W+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h new file mode 100644 index 0000000000000000000000000000000000000000..08198c4caedc927239402496adfd0b3fb18df415 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h @@ -0,0 +1,79 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief The header file contains the following declaration: + * + StepEnum enum definition. + * + PhaseEnum enum definition. + * + UVW_AptReg structure definition. + * + SixStepHandle handle structure definition. + * + AptOutCombination structure definition. + * + Six Step Pwm Function And Six Step Pwm Overlap Function. + */ + +#ifndef MCS_SIX_STEP_H +#define MCS_SIX_STEP_H + +#include "apt.h" + +typedef enum { + STEP1 = 0, + STEP2, + STEP3, + STEP4, + STEP5, + STEP6, + STEP_MAX_NUM +} StepEnum; + +typedef enum { + U = 0, + V, + W, + PHASE_MAX_NUMS +} PhaseEnum; + +typedef enum { + APT_CHA_PWM_CHB_LOW, + APT_CHA_LOW_CHB_HIGH, + APT_CHA_LOW_CHB_LOW +} APT_Act; + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + APT_Handle *u; /**< Apt handle for controlling phase U. */ + APT_Handle *v; /**< Apt handle for controlling phase V. */ + APT_Handle *w; /**< Apt handle for controlling phase W. */ +} UVW_AptReg; + +typedef struct { + unsigned char phaseStep; /* Current step. */ + UVW_AptReg controlApt; /* Apt handles for controlling H bridge. */ +} SixStepHandle; + +typedef struct { + unsigned int upperout; /* High tube level */ + unsigned int upperstate; /* High tube state */ + unsigned int lowerout; /* Low tube level */ + unsigned int lowerstate; /* Low tube state */ +} AptOutCombination; + +void SixStepPwm(const SixStepHandle *handle); +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..d92ed312ac27deafb879eb892affc89d6cf35728 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/func/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 \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/readme.md b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2e0a0107b76aa980d272a06ac27dc8d68834651a --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/mcs_sensorless_bldc_six_step_wave/readme.md @@ -0,0 +1,13 @@ +# Bldc_Sensorless_Six_Step_Wave + +**【功能描述】** ++ 基于反电动势采样的无感电机六步方波调速系统应用 + +**【环境要求】** ++ 所用单板电源为12V低压,电机选用GBM2804H-100T云台电机 + +**【IDE配置方法】** ++ chipConfig中的sample栏目里面选中Bldc Sensorless Six Step Wave示例,然后点击生成代码即可 + +**【注意事项】** ++ 供电电源12V \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled.h new file mode 100644 index 0000000000000000000000000000000000000000..3939b73a4602dd140bf00c504d7d1da211241dd8 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled.h @@ -0,0 +1,46 @@ +#ifndef __OLED__H__ +#define __OLED__H__ + +#define OLED_CMD 0 //写命令 +#define OLED_DATA 1 //写数据 + +#define OLED_MODE 0 +#define SIZE 8 +#define XLevelL 0x00 +#define XLevelH 0x10 +#define Max_Column 128 +#define Max_Row 64 +#define Brightness 0xFF +#define X_WIDTH 128 +#define Y_WIDTH 64 + +BASE_StatusType I2C_Read(unsigned char addr, unsigned char *buffer, unsigned int length); +BASE_StatusType I2C_Write(unsigned char addr, unsigned char data, unsigned int length); + +void OLED_Init(void); + +void OLED_WriteCommand(unsigned char IIC_Command); +void OLED_WriteData(unsigned char IIC_Data); + +void OLED_Write_DataOrCommand(unsigned dat,unsigned cmd); +void OLED_Clear(void); + +void OLED_Display_On(void); + +void OLED_Set_Pos(unsigned char x, unsigned char y); + +void OLED_ShowChar(unsigned char x,unsigned char y,unsigned char chr,unsigned char Char_Size); +void OLED_ShowNum(unsigned char x,unsigned char y,unsigned int num,unsigned char len,unsigned char size); +void OLED_ShowString(unsigned char x,unsigned char y,char *chr,unsigned char Char_Size); + +//显示汉字 +void OLED_displaychina(unsigned char x,unsigned char y,unsigned char *ch); + +void OLED_displaystr(unsigned char col,unsigned char page,unsigned char *str); + +unsigned int oled_pow(unsigned char m,unsigned char n); + + +void OLED_displaychar(unsigned char col,unsigned char page,unsigned char eng); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled_fonts.h b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled_fonts.h new file mode 100644 index 0000000000000000000000000000000000000000..2329281a40b36f93a4d9df2aa075ee8925418495 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/inc/oled_fonts.h @@ -0,0 +1,562 @@ + + + + +//常用ASCII表 +//偏移量32 +//ASCII字符集 +//偏移量32 + +/************************************6*8的点阵************************************/ +const unsigned char F6x8[][6] = { +{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},// sp +{0x00, 0x00, 0x00, 0x2f, 0x00, 0x00},// ! +{0x00, 0x00, 0x07, 0x00, 0x07, 0x00},// " +{0x00, 0x14, 0x7f, 0x14, 0x7f, 0x14},// # +{0x00, 0x24, 0x2a, 0x7f, 0x2a, 0x12},// $ +{0x00, 0x62, 0x64, 0x08, 0x13, 0x23},// % +{0x00, 0x36, 0x49, 0x55, 0x22, 0x50},// & +{0x00, 0x00, 0x05, 0x03, 0x00, 0x00},// ' +{0x00, 0x00, 0x1c, 0x22, 0x41, 0x00},// ( +{0x00, 0x00, 0x41, 0x22, 0x1c, 0x00},// ) +{0x00, 0x14, 0x08, 0x3E, 0x08, 0x14},// * +{0x00, 0x08, 0x08, 0x3E, 0x08, 0x08},// + +{0x00, 0x00, 0x00, 0xA0, 0x60, 0x00},// , +{0x00, 0x08, 0x08, 0x08, 0x08, 0x08},// - +{0x00, 0x00, 0x60, 0x60, 0x00, 0x00},// . +{0x00, 0x20, 0x10, 0x08, 0x04, 0x02},// / +{0x00, 0x3E, 0x51, 0x49, 0x45, 0x3E},// 0 +{0x00, 0x00, 0x42, 0x7F, 0x40, 0x00},// 1 +{0x00, 0x42, 0x61, 0x51, 0x49, 0x46},// 2 +{0x00, 0x21, 0x41, 0x45, 0x4B, 0x31},// 3 +{0x00, 0x18, 0x14, 0x12, 0x7F, 0x10},// 4 +{0x00, 0x27, 0x45, 0x45, 0x45, 0x39},// 5 +{0x00, 0x3C, 0x4A, 0x49, 0x49, 0x30},// 6 +{0x00, 0x01, 0x71, 0x09, 0x05, 0x03},// 7 +{0x00, 0x36, 0x49, 0x49, 0x49, 0x36},// 8 +{0x00, 0x06, 0x49, 0x49, 0x29, 0x1E},// 9 +{0x00, 0x00, 0x36, 0x36, 0x00, 0x00},// : +{0x00, 0x00, 0x56, 0x36, 0x00, 0x00},// ; +{0x00, 0x08, 0x14, 0x22, 0x41, 0x00},// < +{0x00, 0x14, 0x14, 0x14, 0x14, 0x14},// = +{0x00, 0x00, 0x41, 0x22, 0x14, 0x08},// > +{0x00, 0x02, 0x01, 0x51, 0x09, 0x06},// ? +{0x00, 0x32, 0x49, 0x59, 0x51, 0x3E},// @ +{0x00, 0x7C, 0x12, 0x11, 0x12, 0x7C},// A +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x36},// B +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x22},// C +{0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C},// D +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x41},// E +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x01},// F +{0x00, 0x3E, 0x41, 0x49, 0x49, 0x7A},// G +{0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F},// H +{0x00, 0x00, 0x41, 0x7F, 0x41, 0x00},// I +{0x00, 0x20, 0x40, 0x41, 0x3F, 0x01},// J +{0x00, 0x7F, 0x08, 0x14, 0x22, 0x41},// K +{0x00, 0x7F, 0x40, 0x40, 0x40, 0x40},// L +{0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F},// M +{0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F},// N +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E},// O +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x06},// P +{0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E},// Q +{0x00, 0x7F, 0x09, 0x19, 0x29, 0x46},// R +{0x00, 0x46, 0x49, 0x49, 0x49, 0x31},// S +{0x00, 0x01, 0x01, 0x7F, 0x01, 0x01},// T +{0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F},// U +{0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F},// V +{0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F},// W +{0x00, 0x63, 0x14, 0x08, 0x14, 0x63},// X +{0x00, 0x07, 0x08, 0x70, 0x08, 0x07},// Y +{0x00, 0x61, 0x51, 0x49, 0x45, 0x43},// Z +{0x00, 0x00, 0x7F, 0x41, 0x41, 0x00},// [ +{0x00, 0x55, 0x2A, 0x55, 0x2A, 0x55},// 55 +{0x00, 0x00, 0x41, 0x41, 0x7F, 0x00},// ] +{0x00, 0x04, 0x02, 0x01, 0x02, 0x04},// ^ +{0x00, 0x40, 0x40, 0x40, 0x40, 0x40},// _ +{0x00, 0x00, 0x01, 0x02, 0x04, 0x00},// ' +{0x00, 0x20, 0x54, 0x54, 0x54, 0x78},// a +{0x00, 0x7F, 0x48, 0x44, 0x44, 0x38},// b +{0x00, 0x38, 0x44, 0x44, 0x44, 0x20},// c +{0x00, 0x38, 0x44, 0x44, 0x48, 0x7F},// d +{0x00, 0x38, 0x54, 0x54, 0x54, 0x18},// e +{0x00, 0x08, 0x7E, 0x09, 0x01, 0x02},// f +{0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C},// g +{0x00, 0x7F, 0x08, 0x04, 0x04, 0x78},// h +{0x00, 0x00, 0x44, 0x7D, 0x40, 0x00},// i +{0x00, 0x40, 0x80, 0x84, 0x7D, 0x00},// j +{0x00, 0x7F, 0x10, 0x28, 0x44, 0x00},// k +{0x00, 0x00, 0x41, 0x7F, 0x40, 0x00},// l +{0x00, 0x7C, 0x04, 0x18, 0x04, 0x78},// m +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x78},// n +{0x00, 0x38, 0x44, 0x44, 0x44, 0x38},// o +{0x00, 0xFC, 0x24, 0x24, 0x24, 0x18},// p +{0x00, 0x18, 0x24, 0x24, 0x18, 0xFC},// q +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x08},// r +{0x00, 0x48, 0x54, 0x54, 0x54, 0x20},// s +{0x00, 0x04, 0x3F, 0x44, 0x40, 0x20},// t +{0x00, 0x3C, 0x40, 0x40, 0x20, 0x7C},// u +{0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C},// v +{0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C},// w +{0x00, 0x44, 0x28, 0x10, 0x28, 0x44},// x +{0x00, 0x1C, 0xA0, 0xA0, 0xA0, 0x7C},// y +{0x00, 0x44, 0x64, 0x54, 0x4C, 0x44},// z +{0x14, 0x14, 0x14, 0x14, 0x14, 0x14},// horiz lines +}; + +/****************************************8*16的点阵************************************/ +const unsigned char F8X16[]={ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,// 0 + 0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x00,//! 1 + 0x00,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//" 2 + 0x40,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x00,//# 3 + 0x00,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x00,//$ 4 + 0xF0,0x08,0xF0,0x00,0xE0,0x18,0x00,0x00,0x00,0x21,0x1C,0x03,0x1E,0x21,0x1E,0x00,//% 5 + 0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x24,0x19,0x27,0x21,0x10,//& 6 + 0x10,0x16,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//' 7 + 0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,//( 8 + 0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,//) 9 + 0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,//* 10 + 0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x1F,0x01,0x01,0x01,0x00,//+ 11 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xB0,0x70,0x00,0x00,0x00,0x00,0x00,//, 12 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,//- 13 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,//. 14 + 0x00,0x00,0x00,0x00,0x80,0x60,0x18,0x04,0x00,0x60,0x18,0x06,0x01,0x00,0x00,0x00,/// 15 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,//0 16 + 0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//1 17 + 0x00,0x70,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,//2 18 + 0x00,0x30,0x08,0x88,0x88,0x48,0x30,0x00,0x00,0x18,0x20,0x20,0x20,0x11,0x0E,0x00,//3 19 + 0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00,//4 20 + 0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00,//5 21 + 0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00,//6 22 + 0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00,//7 23 + 0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,//8 24 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x00,0x31,0x22,0x22,0x11,0x0F,0x00,//9 25 + 0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,//: 26 + 0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x00,0x00,0x00,0x00,//; 27 + 0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,//< 28 + 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x00,//= 29 + 0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,//> 30 + 0x00,0x70,0x48,0x08,0x08,0x08,0xF0,0x00,0x00,0x00,0x00,0x30,0x36,0x01,0x00,0x00,//? 31 + 0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x24,0x23,0x14,0x0B,0x00,//@ 32 + 0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,//A 33 + 0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,//B 34 + 0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,//C 35 + 0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,//D 36 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,//E 37 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,//F 38 + 0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,//G 39 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,//H 40 + 0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//I 41 + 0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,//J 42 + 0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,//K 43 + 0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,//L 44 + 0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x00,0x3F,0x00,0x3F,0x20,0x00,//M 45 + 0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,//N 46 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,//O 47 + 0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,//P 48 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x18,0x24,0x24,0x38,0x50,0x4F,0x00,//Q 49 + 0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,//R 50 + 0x00,0x70,0x88,0x08,0x08,0x08,0x38,0x00,0x00,0x38,0x20,0x21,0x21,0x22,0x1C,0x00,//S 51 + 0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//T 52 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//U 53 + 0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,//V 54 + 0xF8,0x08,0x00,0xF8,0x00,0x08,0xF8,0x00,0x03,0x3C,0x07,0x00,0x07,0x3C,0x03,0x00,//W 55 + 0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,//X 56 + 0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//Y 57 + 0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,//Z 58 + 0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,//[ 59 + 0x00,0x0C,0x30,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,//\ 60 + 0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,//] 61 + 0x00,0x00,0x04,0x02,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//^ 62 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,//_ 63 + 0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//` 64 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x19,0x24,0x22,0x22,0x22,0x3F,0x20,//a 65 + 0x08,0xF8,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,//b 66 + 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,//c 67 + 0x00,0x00,0x00,0x80,0x80,0x88,0xF8,0x00,0x00,0x0E,0x11,0x20,0x20,0x10,0x3F,0x20,//d 68 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x22,0x13,0x00,//e 69 + 0x00,0x80,0x80,0xF0,0x88,0x88,0x88,0x18,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//f 70 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,//g 71 + 0x08,0xF8,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//h 72 + 0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//i 73 + 0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,//j 74 + 0x08,0xF8,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x02,0x2D,0x30,0x20,0x00,//k 75 + 0x00,0x08,0x08,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//l 76 + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,//m 77 + 0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//n 78 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//o 79 + 0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0xA1,0x20,0x20,0x11,0x0E,0x00,//p 80 + 0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0xA0,0xFF,0x80,//q 81 + 0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,//r 82 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,//s 83 + 0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x00,0x00,//t 84 + 0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,//u 85 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x01,0x0E,0x30,0x08,0x06,0x01,0x00,//v 86 + 0x80,0x80,0x00,0x80,0x00,0x80,0x80,0x80,0x0F,0x30,0x0C,0x03,0x0C,0x30,0x0F,0x00,//w 87 + 0x00,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x31,0x2E,0x0E,0x31,0x20,0x00,//x 88 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x80,0x81,0x8E,0x70,0x18,0x06,0x01,0x00,//y 89 + 0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,//z 90 + 0x00,0x00,0x00,0x00,0x80,0x7C,0x02,0x02,0x00,0x00,0x00,0x00,0x00,0x3F,0x40,0x40,//{ 91 + 0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,//| 92 + 0x00,0x02,0x02,0x7C,0x80,0x00,0x00,0x00,0x00,0x40,0x40,0x3F,0x00,0x00,0x00,0x00,//} 93 + 0x00,0x06,0x01,0x01,0x02,0x02,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//~ 94 +}; + + +unsigned char Aciss_8X16[]={ +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*" ",0*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x00,/*"!",1*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x0C,0x02,0x10,0x0C,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*""",2*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0xC0,0x78,0x40,0xC0,0x78,0x00,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x00,/*"#",3*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x88,0xFC,0x08,0x30,0x00,0x00,0x18,0x20,0x20,0xFF,0x21,0x1E,0x00,/*"$",4*/ +/* (8 X 16 , 宋体 )*/ + +0xF0,0x08,0xF0,0x80,0x60,0x18,0x00,0x00,0x00,0x31,0x0C,0x03,0x1E,0x21,0x1E,0x00,/*"%",5*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x2C,0x19,0x27,0x21,0x10,/*"&",6*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x12,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"'",7*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,/*"(",8*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,/*")",9*/ +/* (8 X 16 , 宋体 )*/ + +0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,/*"*",10*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x0F,0x01,0x01,0x01,/*"+",11*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x70,0x00,0x00,0x00,0x00,0x00,/*",",12*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x00,/*"-",13*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,/*".",14*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xC0,0x38,0x04,0x00,0x00,0x60,0x18,0x07,0x00,0x00,0x00,0x00,/*"/",15*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,/*"0",16*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,/*"1",17*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x08,0x08,0x08,0x08,0xF0,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,/*"2",18*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x30,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x18,0x20,0x21,0x21,0x22,0x1C,0x00,/*"3",19*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x30,0xF8,0x00,0x00,0x00,0x06,0x05,0x24,0x24,0x3F,0x24,0x24,/*"4",20*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF8,0x88,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x20,0x20,0x20,0x11,0x0E,0x00,/*"5",21*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x88,0x88,0x90,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x20,0x1F,0x00,/*"6",22*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x18,0x08,0x08,0x88,0x68,0x18,0x00,0x00,0x00,0x00,0x3E,0x01,0x00,0x00,0x00,/*"7",23*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,/*"8",24*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x08,0x08,0x10,0xE0,0x00,0x00,0x01,0x12,0x22,0x22,0x11,0x0F,0x00,/*"9",25*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,/*":",26*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,/*";",27*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,/*"<",28*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00,/*"=",29*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,/*">",30*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x48,0x08,0x08,0x88,0x70,0x00,0x00,0x00,0x00,0x30,0x37,0x00,0x00,0x00,/*"?",31*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x28,0x2F,0x28,0x17,0x00,/*"@",32*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,/*"A",33*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,/*"B",34*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,/*"C",35*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,/*"D",36*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,/*"E",37*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,/*"F",38*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,/*"G",39*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,/*"H",40*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"I",41*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,/*"J",42*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,/*"K",43*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,/*"L",44*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x01,0x3E,0x01,0x3F,0x20,0x00,/*"M",45*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,/*"N",46*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,/*"O",47*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,/*"P",48*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x28,0x28,0x30,0x50,0x4F,0x00,/*"Q",49*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,/*"R",50*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",51*/ +/* (8 X 16 , 宋体 )*/ + +0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"T",52*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"U",53*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,/*"V",54*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x00,0xF8,0x00,0xF8,0x08,0x00,0x00,0x03,0x3E,0x01,0x3E,0x03,0x00,0x00,/*"W",55*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",56*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"Y",57*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,/*"Z",58*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,/*"[",59*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x04,0x38,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,/*"\",60*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,/*"]",61*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x04,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"^",62*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,/*"_",63*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"`",64*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x19,0x24,0x24,0x12,0x3F,0x20,0x00,/*"a",65*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,/*"b",66*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,/*"c",67*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x90,0xF0,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"d",68*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x24,0x24,0x24,0x24,0x17,0x00,/*"e",69*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x90,0x90,0x20,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"f",70*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,/*"g",71*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"h",72*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"i",73*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,/*"j",74*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x06,0x29,0x30,0x20,0x00,/*"k",75*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"l",76*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,/*"m",77*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"n",78*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"o",79*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0x91,0x20,0x20,0x11,0x0E,0x00,/*"p",80*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x00,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0x91,0xFF,0x80,/*"q",81*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,/*"r",82*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,/*"s",83*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x10,0x00,/*"t",84*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"u",85*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x03,0x0C,0x30,0x0C,0x03,0x00,0x00,/*"v",86*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x80,0x80,0x01,0x0E,0x30,0x0C,0x07,0x38,0x06,0x01,/*"w",87*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x20,0x31,0x0E,0x2E,0x31,0x20,0x00,/*"x",88*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x81,0x86,0x78,0x18,0x06,0x01,0x00,/*"y",89*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,/*"z",90*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0xFC,0x02,0x02,0x00,0x00,0x00,0x00,0x01,0x3E,0x40,0x40,/*"{",91*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,/*"|",92*/ +/* (8 X 16 , 宋体 )*/ + +0x02,0x02,0xFC,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x3E,0x01,0x00,0x00,0x00,0x00,/*"}",93*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x01,0x02,0x02,0x04,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"~",94*/ +/* (8 X 16 , 宋体 )*/ + +}; +//确定汉字字模数据位置 +const unsigned char indexs[][2]={"基","于","海","思","单","片","机","智","能","中","专","速","度","一", +"二","三","四","五","档","位","电"}; + + +const unsigned char Hzk[][32]={ +{0x00,0x04,0x04,0x04,0xFF,0x54,0x54,0x54,0x54,0x54,0xFF,0x04,0x04,0x04,0x00,0x00}, +{0x11,0x11,0x89,0x85,0x93,0x91,0x91,0xFD,0x91,0x91,0x93,0x85,0x89,0x11,0x11,0x00},/*"基",0*/ +{0x40,0x40,0x42,0x42,0x42,0x42,0x42,0xFE,0x42,0x42,0x42,0x42,0x42,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x40,0x80,0x7F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"于",1*/ +{0x10,0x60,0x02,0x0C,0xC0,0x10,0x08,0xF7,0x14,0x54,0x94,0x14,0xF4,0x04,0x00,0x00}, +{0x04,0x04,0x7C,0x03,0x00,0x01,0x1D,0x13,0x11,0x55,0x99,0x51,0x3F,0x11,0x01,0x00},/*"海",2*/ +{0x00,0x00,0xFE,0x92,0x92,0x92,0x92,0xFE,0x92,0x92,0x92,0x92,0xFE,0x00,0x00,0x00}, +{0x40,0x38,0x01,0x00,0x3C,0x40,0x40,0x42,0x4C,0x40,0x40,0x70,0x05,0x08,0x30,0x00},/*"思",3*/ +{0x00,0x00,0xF8,0x49,0x4A,0x4C,0x48,0xF8,0x48,0x4C,0x4A,0x49,0xF8,0x00,0x00,0x00}, +{0x10,0x10,0x13,0x12,0x12,0x12,0x12,0xFF,0x12,0x12,0x12,0x12,0x13,0x10,0x10,0x00},/*"单",4*/ +{0x00,0x00,0x00,0xFE,0x20,0x20,0x20,0x20,0x20,0x3F,0x20,0x20,0x20,0x20,0x00,0x00}, +{0x00,0x80,0x60,0x1F,0x02,0x02,0x02,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x00},/*"片",5*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x00,0xFE,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x83,0x60,0x1F,0x00,0x00,0x00,0x3F,0x40,0x40,0x78,0x00},/*"机",6*/ +{0x10,0x94,0x53,0x32,0x1E,0x32,0x52,0x10,0x00,0x7E,0x42,0x42,0x42,0x7E,0x00,0x00}, +{0x00,0x00,0x00,0xFF,0x49,0x49,0x49,0x49,0x49,0x49,0x49,0xFF,0x00,0x00,0x00,0x00},/*"智",7*/ +{0x08,0xCC,0x4A,0x49,0x48,0x4A,0xCC,0x18,0x00,0x7F,0x88,0x88,0x84,0x82,0xE0,0x00}, +{0x00,0xFF,0x12,0x12,0x52,0x92,0x7F,0x00,0x00,0x7E,0x88,0x88,0x84,0x82,0xE0,0x00},/*"能",8*/ +{0x00,0x00,0xF0,0x10,0x10,0x10,0x10,0xFF,0x10,0x10,0x10,0x10,0xF0,0x00,0x00,0x00}, +{0x00,0x00,0x0F,0x04,0x04,0x04,0x04,0xFF,0x04,0x04,0x04,0x04,0x0F,0x00,0x00,0x00},/*"中",9*/ +{0x40,0x40,0x48,0x48,0x48,0xC8,0x78,0x4F,0x48,0x48,0x48,0x48,0x48,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x03,0x12,0x12,0x22,0x22,0x52,0x8A,0x06,0x00,0x00,0x00,0x00},/*"专",10*/ + +{0x40,0x40,0x42,0xCC,0x00,0x04,0xF4,0x94,0x94,0xFF,0x94,0x94,0xF4,0x04,0x00,0x00}, +{0x00,0x40,0x20,0x1F,0x20,0x48,0x44,0x42,0x41,0x5F,0x41,0x42,0x44,0x48,0x40,0x00},/*"速",11*/ +{0x00,0x00,0xFC,0x24,0x24,0x24,0xFC,0x25,0x26,0x24,0xFC,0x24,0x24,0x24,0x04,0x00}, +{0x40,0x30,0x8F,0x80,0x84,0x4C,0x55,0x25,0x25,0x25,0x55,0x4C,0x80,0x80,0x80,0x00},/*"度",12*/ +{0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"一",13*/ +{0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,0x00}, +{0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x00},/*"二",14*/ +{0x00,0x04,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x04,0x00,0x00}, +{0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x00},/*"三",15*/ +{0x00,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x00,0x00}, +{0x00,0x7F,0x28,0x24,0x23,0x20,0x20,0x20,0x20,0x21,0x22,0x22,0x22,0x7F,0x00,0x00},/*"四",16*/ +{0x00,0x02,0x42,0x42,0x42,0xC2,0x7E,0x42,0x42,0x42,0x42,0xC2,0x02,0x02,0x00,0x00}, +{0x40,0x40,0x40,0x40,0x78,0x47,0x40,0x40,0x40,0x40,0x40,0x7F,0x40,0x40,0x40,0x00},/*"五",17*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x40,0x42,0x5C,0x40,0x7F,0x40,0x50,0xCE,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x01,0x40,0x44,0x44,0x44,0x44,0x44,0x44,0xFF,0x00,0x00},/*"档",18*/ +{0x00,0x80,0x60,0xF8,0x07,0x10,0x90,0x10,0x11,0x16,0x10,0x10,0xD0,0x10,0x00,0x00}, +{0x01,0x00,0x00,0xFF,0x40,0x40,0x41,0x5E,0x40,0x40,0x70,0x4E,0x41,0x40,0x40,0x00},/*"位",19*/ +{0x00,0x00,0xF8,0x88,0x88,0x88,0x88,0xFF,0x88,0x88,0x88,0x88,0xF8,0x00,0x00,0x00}, +{0x00,0x00,0x1F,0x08,0x08,0x08,0x08,0x7F,0x88,0x88,0x88,0x88,0x9F,0x80,0xF0,0x00},/*"电",20*/ + + + + +}; + + + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/src/oled.c b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/src/oled.c new file mode 100644 index 0000000000000000000000000000000000000000..355dd0d14c15bb5dab38017d6d7a36ebcfbdea70 --- /dev/null +++ b/vendor/yibaina_3061M/E7050_oled_ifd_sample/user/oled/src/oled.c @@ -0,0 +1,352 @@ +#include "main.h" +#include "debug.h" +#include "oled_fonts.h" +#include "oled.h" +#include + +#define OLED_WRITE_REG 0x78 //0x78 ap3216 0x3C +#define OLED_READ_REG OLED_WRITE_REG+1 + +#define I2C_SAMPLE_OLED_PAGE_SIZE 7//一次写一个字节 +#define I2C_SAMPLE_OLED_ADDR_SIZE 1 +#define I2C_SAMPLE_MAX_TIMEOUT 10000 + + + + +/** + * @brief 在阻塞模式下读取数据 + * @param addr 要读取的寄存器地址 + * @param buffer 用于存储读取数据的缓冲区 + * @param length 要读取的数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Read(unsigned char addr, unsigned char *buffer, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 存储要读取的寄存器地址 + unsigned char tempAddr[I2C_SAMPLE_OLED_ADDR_SIZE]; + tempAddr[0] = addr; + + // 发送寄存器地址 + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempAddr, I2C_SAMPLE_OLED_ADDR_SIZE); + + // 发送寄存器地址是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + + /* 从设备读取数据 */ + ret = HAL_I2C_MasterReadDMA(&g_i2c0, OLED_READ_REG, buffer, length); + + // 从寄存器地址读取数据是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + return ret; +} + +/** + * @brief 在阻塞模式下写入数据 + * @param addr 寄存器地址 + * @param data 要写入的数据 + * @param length 数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Write(unsigned char addr, unsigned char data, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 使用两个字节的数组,存储写寄存器地址和发送数据 + unsigned char tempWrite[I2C_SAMPLE_OLED_PAGE_SIZE + I2C_SAMPLE_OLED_ADDR_SIZE]; + tempWrite[0] = addr; // 要写入的寄存器地址 + tempWrite[1] = data; // 要写入的数据 + + // 写入的寄存器地址长度+写入的数据长度(2字节) + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempWrite, I2C_SAMPLE_OLED_ADDR_SIZE + length); + + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Write Data Fail!,ret:%d\r\n", __LINE__, ret); + } + return ret; +} + +// OLED屏幕初始化 +void OLED_Init(void) +{ + BASE_FUNC_DELAY_MS(100); + I2C_Write(0x00, 0xAE, 1); // 关闭显示 + I2C_Write(0x00, 0x00, 1); // 设置低列地址 + I2C_Write(0x00, 0x10, 1); // 设置高列地址 + I2C_Write(0x00, 0x40, 1); // 设置起始行地址 + I2C_Write(0x00, 0xB0, 1); // 设置页面寻址模式的起始页地址,0-7 + I2C_Write(0x00, 0x81, 1); // 设置对比度控制寄存器 + I2C_Write(0x00, 0xFF, 1); // 对比度调节 0x00~0xff + I2C_Write(0x00, 0xA1, 1); // 设置段重映射 0 到 127 + I2C_Write(0x00, 0xA6, 1); // 设置正常显示 + I2C_Write(0x00, 0xA8, 1); // 设置多重扫描比率(1 到 64) + I2C_Write(0x00, 0x3F, 1); // 设置多重扫描比率的具体值 + I2C_Write(0x00, 0xC8, 1); // 设置COM输出扫描方向 + I2C_Write(0x00, 0xD3, 1); // 设置显示偏移 + I2C_Write(0x00, 0x00, 1); // 不偏移 + I2C_Write(0x00, 0xD5, 1); // 设置显示时钟分频比/振荡器频率 + I2C_Write(0x00, 0x80, 1); // 设置分频比 + I2C_Write(0x00, 0xD8, 1); // 设置预充电周期 + I2C_Write(0x00, 0x05, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xD9, 1); // 设置预充电周期 + I2C_Write(0x00, 0xF1, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xDA, 1); // 设置COM引脚硬件配置 + I2C_Write(0x00, 0x12, 1); // 设置COM引脚硬件配置的具体值 + I2C_Write(0x00, 0xDB, 1); // 设置VCOMH + I2C_Write(0x00, 0x30, 1); // 设置VCOMH的具体值 0x20, 0.77xVcc + I2C_Write(0x00, 0x8D, 1); // 设置DC-DC使能 + I2C_Write(0x00, 0x14, 1); // 设置DC-DC使能的具体值 + I2C_Write(0x00, 0xAF, 1); // 打开OLED面板 + OLED_Clear(); // 清屏 +} + +// 写命令 +void OLED_WriteCommand(unsigned char dat){ + I2C_Write(0x00,dat,1); +} + +// 写数据 +void OLED_WriteData(unsigned char dat){ + I2C_Write(0x40,dat,1); +} + +// 区别是写数据还是写命令 +void OLED_Write_DataOrCommand(unsigned dat,unsigned cmd) +{ + if(cmd){ + OLED_WriteData(dat); + } + else{ + OLED_WriteCommand(dat); + } +} + +// 清屏 +void OLED_Clear(void) +{ + unsigned char i, n; + for (i = 0; i < 8; i++) + { + OLED_Write_DataOrCommand(0xb0 + i, OLED_CMD); // 设置页地址(0~7) + OLED_Write_DataOrCommand(0x02, OLED_CMD); // 设置显示位置—列低地址 0x00 + OLED_Write_DataOrCommand(0x10, OLED_CMD); // 设置显示位置—列高地址 + for (n = 0; n < 128; n++) + OLED_Write_DataOrCommand(0, OLED_DATA); + } // 更新显示 +} + +// 开启OLED +void OLED_Display_On(void) +{ + OLED_Write_DataOrCommand(0X8D, OLED_CMD); // 设置电荷泵 + OLED_Write_DataOrCommand(0X14, OLED_CMD); // 开启电荷泵 + OLED_Write_DataOrCommand(0XAF, OLED_CMD); // OLED唤醒 +} + +// 设置起始点坐标 +void OLED_Set_Pos(unsigned char x, unsigned char y) +{ + OLED_Write_DataOrCommand(0xb0 + y, OLED_CMD); + OLED_Write_DataOrCommand((((x + 2) & 0xf0) >> 4) | 0x10, OLED_CMD); // 取高位 + OLED_Write_DataOrCommand(((x + 2) & 0x0f), OLED_CMD); // 取低位 +} + +// 显示字符 +void OLED_ShowChar(unsigned char x,unsigned char y,unsigned char chr,unsigned char Char_Size) +{ + unsigned char c = 0, i = 0; + c = chr - ' '; // 得到偏移后的值 + if (x > Max_Column - 1) + { + x = 0; + y = y + 2; + } + if (Char_Size == 16) + { + OLED_Set_Pos(x, y); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i], OLED_DATA); + OLED_Set_Pos(x, y + 1); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i + 8], OLED_DATA); + } + else + { + OLED_Set_Pos(x, y); + for (i = 0; i < 6; i++) + OLED_Write_DataOrCommand(F6x8[c][i], OLED_DATA); + } +} + + + +void OLED_displaychar(unsigned char col,unsigned char page,unsigned char eng) +{ + unsigned char font_res=0; + + font_res=eng-' '; //在ACISS的第几次位 + + for(unsigned char i=0;i<2;i++) + { + //设置显示位置 + OLED_WriteCommand(0x00 + (col & 0x0f));//设置低位列地址 + OLED_WriteCommand(0x10 + ((col & 0xf0)>>4));//设置高位列地址 + OLED_WriteCommand(0xb0+page+i);//设置页地址 + for(unsigned char j=0;j<8;j++) + { + OLED_WriteData(Aciss_8X16[16*font_res+8*i+j]); + } + } +} + + + +//显示2个数字 +//x,y :起点坐标 +//len :数字的位数 +//size:字体大小 +//mode:模式 0,填充模式;1,叠加模式 +//num:数值(0~4294967295); + +void OLED_ShowNum(unsigned char x,unsigned char y,unsigned int num,unsigned char len,unsigned char size2) +{ + unsigned char t,temp; + unsigned char enshow = 0; + for (t = 0; t < len; t++) + { + temp = (num / oled_pow(10, len - t - 1)) % 10; // 根据位数来显示数字 + if (enshow == 0 && t < (len - 1)) + { + if (temp == 0) + { + OLED_ShowChar(x + (size2)*t, y, ' ', size2); + continue; + } + else + enshow = 1; + } + OLED_ShowChar(x + (size2)*t, y, temp + '0', size2); // ? + } +} + + +//显示一个字符号串 +void OLED_ShowString(unsigned char x,unsigned char y,char *chr,unsigned char Char_Size) +{ + unsigned char j = 0; + while (chr[j] != '\0') + { + OLED_ShowChar(x, y, chr[j], Char_Size); + x += 8; + if (x > 120) +{ + x = 0; + y += 2; + } + j++; + } +} + + + + + +void OLED_displaychina(unsigned char x,unsigned char y,unsigned char *ch) +{ + int t,adder=0; + unsigned char k; + //确定汉字在小字库的位置 + for(k=0;k< sizeof(indexs) /sizeof(indexs[0]);k++) + { + if(*ch == indexs[k][0] && *(ch+1)==indexs[k][1]) + break; + } + + OLED_Set_Pos(x,y); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k][t],OLED_DATA); + adder+=1; + } + OLED_Set_Pos(x,y+1); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k+1][t],OLED_DATA); + adder+=1; + } + + +} + +/* +Function name: OLED_displaystr +Description:OLED显字符串 +param: u8 col 列位置 + u8 page 行位置 + u8 *str 字符串 +retval: void +Remarks: + + +*/ + + +void OLED_displaystr(unsigned char col,unsigned char page,unsigned char *str) +{ + while(*str !='\0') + { + if(*str >= 0xA1)//显示汉字 + { + OLED_displaychina(col,page,str); + str+=3; + col+=16; + } + else//显示英文 + { + OLED_displaychar(col,page,*str); + str+=1; + col+=8; + } + + } +} + + + + + +// /***********功能描述:显示显示BMP图片128×64起始点坐标(x,y),x的范围0~127,y为页的范围0~7*****************/ +// void OLED_DrawBMP(unsigned char x0, unsigned char y0,unsigned char x1, unsigned char y1,unsigned char BMP[]) +// { +// unsigned int j=0; +// unsigned char x,y; + +// if(y1%8==0) y=y1/8; +// else y=y1/8+1; +// for(y=y0;ySC_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 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/yibaina_3061M/GIM4310-10_FOC/user/main.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..f16312ae81c0f869b934b5f3d911845477656c34 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/main.c @@ -0,0 +1,71 @@ +/** + * @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. + * @date 2025-04-17 15:09:50 + */ + +#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; +/* 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 diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..dea3ad66fde865889d8480d222b97f3900bd7dac --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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; /**< Motor start/stop status flag. */ + 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; /**< Current sampling mode setting: single resistor, double resistor. */ + 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; /**< Dual-resistance/three-resistance sampling SVPWM Handle. */ + R1SVPWM_Handle r1Sv; /**< Single-resistance phase-shifted SVPWM handle. */ + 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; /**< Motor protect status detection flag bit handle. */ +} MTRCTRL_Handle; + +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h new file mode 100644 index 0000000000000000000000000000000000000000..38c00b5ddbf9f63ab1a2e5b644eea55d634727ad --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_chip_config.h @@ -0,0 +1,76 @@ +/** + * @ 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" + +#if defined (CHIP_3061MNPICA) || defined (CHIP_3061MNPIKA) || defined (CHIP_3061MNNICA) || \ + defined (CHIP_3061MNNIKA) || defined (CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) || \ + defined (CHIP_3061MNPIK8) || defined (CHIP_3061MNNIK8) + + #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) || defined (CHIP_3066MNPIRH) || \ + defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) + + #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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_ctlmode_config.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6f38cccf3fb92d52b4874390805a520e255b2f --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..783bf21402d5d3f5d4bdc8dc5bd9ee425d0fbf21 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..19510c78b2d63a46ca51495d8ad028e351574d1d --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..19e1f89fd4afbee78702c05249dfbac2a10de7ce --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/inc/mcs_user_config.h @@ -0,0 +1,120 @@ +/** + * @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 /* Capacitor charging time. */ + +#define INV_VOLTAGE_BUS 24.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. */ + +#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 /* SMO4TH PLL Bandwidth. */ +#define SMO4TH_KD 300.0f /* SMO4TH parameters KD. */ +#define SMO4TH_KQ 600.0f /* SMO4TH parameters KQ. */ +#define SMO4TH_SPD_FILTER_CUTOFF_FREQ 40.0f /* SMO4TH speed cutoff frequency of speed filter. */ + +/* User_Commond */ +#define CTRL_IF_CURR_AMP_A 0.8f /* IF control current amplitude. */ +#define USER_TARGET_SPD_HZ 30.0f /* User-defined target speed value. */ +#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 24.0f /* User-defined maximum speed value. */ +#define USER_MIN_SPD_HZ 5.0f /* User-defined minimum speed value. */ +#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 /* Current loop Q axis Kp. */ +#define CURRQAXIS_KI 20612.84f /* Current loop Q axis Ki. */ +#define CURRDAXIS_KP 3.477114f /* Current loop D axis Kp. */ +#define CURRDAXIS_KI 20612.84f /* Current loop D axis Ki. */ +/* Current loop PID output lower limit. */ +#define CURR_LOWERLIM (-INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) +/* Current loop PID output upper limit. */ +#define CURR_UPPERLIM (INV_VOLTAGE_BUS * ONE_DIV_SQRT3 * 0.98f) + +#define SPD_KP 0.00505f /* Speed loop Kp. */ +#define SPD_KI 0.012f /* Speed loop Ki. */ +#define SPD_LOWERLIM (-0.105f) /* Speed loop PID output lower limit. */ +#define SPD_UPPERLIM 0.105f /* Speed loop PID output upper limit. */ + +/* 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, \ +// .busVolt = INV_VOLTAGE_BUS, \ +// } + +// // GIM4310-10 +#define MOTORPARAM_DEFAULTS { \ + .mtrNp = 14, \ + .mtrRs = 1.046f, \ + .mtrLd = 0.000344f, \ + .mtrLq = 0.000344f, \ + .mtrPsif = 0.0f, \ + .mtrJ = 0.0f, \ + .maxElecSpd = 24.0f, \ + .maxCurr = 0.8f, \ + .busVolt = INV_VOLTAGE_BUS, \ +} +/* Bus voltage sampling conversion factor. */ +#define ADC_UDC_COFFI 0.01289f /* 0.01289 = 3.3/4096*192/12. */ + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.c new file mode 100644 index 0000000000000000000000000000000000000000..99766bdf9b3d4f161b1902708696cb0e75a4fc9c --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_cmm.h new file mode 100644 index 0000000000000000000000000000000000000000..104a5decba9eeb22375b63e4def4278af37d3573 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.c new file mode 100644 index 0000000000000000000000000000000000000000..e97876b7c6ec522fa82c30cbe503e2ab8de288db --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user.h new file mode 100644 index 0000000000000000000000000000000000000000..365110e10c6cd8bd5207af61f0a87b6df226fa91 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/common/mcs_prot_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..c0564a22799334684539fffc1897c7941a076370 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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 (1.5f) +/**< 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 (26.0f) /**<处于1级时,直流链路电压触发值(V)过高*/ +#define PROT_OVER_VOLT_BRK_ON2 (27.0f) /**< Over dc-link voltage trigger value (V) when in level 2. */ +#define PROT_OVER_VOLT_BRK_ON3 (28.0f) /**< Over dc-link voltage trigger value (V) when in level 3. */ +#define PROT_OVER_VOLT_BRK_ALL (30.0f) /**< Over dc-link voltage trigger value (V) when in level 4. */ +#define PROT_OVER_VOLT_RECY_DELTA (0.5f) /**<从保护状态恢复时的电压间隙(V)*/ +#define PROT_OVER_VOLT_LIMIT1_TIME_SEC (5.0f) /** 1; One-cycle mode: < 0.5 */ +#define POS_SNSR_IPD_INJ_PERIOD (4) + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..da4e56f89a51d39053fad4511bb799c91070df65 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_curr_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..e9916fe491699bff3373bbc68b175b6db16d7cd7 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..b0541a2e2e37ba98e8b92e6334ab2cc940b72b6c --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_dc_volt_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..0435156a0add386ec4b783f4d003f4178baa2ecf --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee4d2d240e66f7cfb0528b2d42d4c32ada0078 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_motor_stalling.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d1e4bed11bec0d6d73aee54de36c365588898e --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..184ba4a3ac712690e4f808f1464a65c74a387b52 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/protection/mcs_temp_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9d99a76c19f53a78ccc1257287eccfd1fc972c --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/readme.md b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..98b2a068ddfaef196002273aaedc90123a0cd0de --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/readme.md @@ -0,0 +1,10 @@ +# pmsm_sensorless_2shunt_foc + +**【功能描述】** ++ 基于ECMCU105H/ECBMCU201MPC单板的单电机双电阻采样Foc应用 + +**【环境要求】** ++ 所有单板电源改制为演示用的12V低压,电机选用Gimbal GBM2804H-100T + +**【IDE配置方法】** ++ chipConfig中的Sample栏目里面选中pmsm sensorless 2shunt foc示例,然后点击生成代码即可 diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..9fc8afac32ecb5810db6758fb6acbca42a4c0f69 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..f754d001938e6d12d2688174138c46a200717703 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/src/mcs_motor_process.c @@ -0,0 +1,951 @@ +/** + * @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}; + +/* 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.adc0Compensate = ADC0COMPENSATE; /* Phase-u current init adc shift trim value */ + g_mc.adc1Compensate = ADC1COMPENSATE; /* Phase-w current init adc shift trim value */ + + 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); + if (g_mc.sampleMode == DUAL_RESISTORS) { + SVPWM_Init(&g_mc.sv, INV_VOLTAGE_BUS * ONE_DIV_SQRT3); /* Dual resistors SVPWM init. */ + } else if (g_mc.sampleMode == SINGLE_RESISTOR) { + /* Single resistor SVPWM init. */ + 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. + * @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. + * @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. + * @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; + } + } + if (adcSampleTimes < 1.0f) { + adcSampleTimes = 1.0f; /* Prevent divide-by-zero errors */ + } + 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. + * @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. + * @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. + * @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 = 0.0f; + /* 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); + static float potentiomitorAdcValue = 0.0f; + static float spdCmdHz = 0; + static float spdCmdHzLast = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHzLast init value */ + HAL_ADC_SoftTrigSample(&ADCPTT_HANDLE, ADCPTTSOCNUM); + BASE_FUNC_DELAY_US(10); /* Delay 10 us. */ + potentiomitorAdcValue = (float)HAL_ADC_GetConvResult(&ADCPTT_HANDLE, ADCPTTSOCNUM); + /* 4045.0 is adc sample max value of potentiomitor, convert max spd to 180.25Hz */ + spdCmdHz = potentiomitorAdcValue / 4045.0f * USER_MAX_SPD_HZ; + if (Abs(spdCmdHzLast - spdCmdHz) < 1.0f) { /* Ignore changes less than 1. */ + return; + } + spdCmdHzLast = spdCmdHz; + if (spdCmdHz < USER_MIN_SPD_HZ) { /* 35.0 is spdCmdHz lower limit */ + spdCmdHz = USER_MIN_SPD_HZ; /* 35.0 is spdCmdHz lower limit */ + } + if (spdCmdHz > g_mc.mtrParam.maxElecSpd) { /* spdCmdHz upper limit */ + spdCmdHz = g_mc.mtrParam.maxElecSpd; /* spdCmdHz upper limit */ + } + if (g_mc.spdAdjustMode == CUST_SPEED_ADJUST) { + g_mc.spdCmdHz = spdCmdHz; + } +} + +/** + * @brief System timer ISR for Motor Statemachine CallBack function. + * @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. */ + 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 */ + g_mc.readCurrUvwCb = ReadCurrUvw; + g_mc.setPwmDutyCb = SetPwmDutyCp; + g_mc.setADCTriggerTimeCb = SetADCTriggerTime; +} + +/** + * @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); + } + } +} + +/** + * @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); + + /* Disable PWM output before startup. */ + + 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); + while (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 */ + 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; + } + } + return 0; +} diff --git a/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.c new file mode 100644 index 0000000000000000000000000000000000000000..7c4f75252f9cb7a7fd3b2452ad276e8074519121 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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); + float pllBdw = 0.0f; + switch (cmdCode) { + case SET_SMO1TH_PLL_BDW: /* Set the bandwidth. */ + pllBdw = rxData->data[DATA_SEGMENT_THREE].typeF; + smoHandle->pll.pi.kp = 2.0f * pllBdw; /* kp = 2.0f * pllBdw */ + smoHandle->pll.pi.ki = pllBdw * pllBdw; /* ki = pllBdw * pllBdw */ + ackCode = 0X0A; + CUST_AckCode(g_uartTxBuf, ackCode, 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) +{ + float pllBdw = rxData->data[DATA_SEGMENT_TWO].typeF; + smo4thHandle->pll.pi.kp = (2.0f) * pllBdw; /* kp = 2.0f * pllBdw */ + smo4thHandle->pll.pi.ki = pllBdw * pllBdw; + ackCode = 0X11; + CUST_AckCode(g_uartTxBuf, ackCode, 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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/cust_process.h new file mode 100644 index 0000000000000000000000000000000000000000..60fe69bb966d5f398468c8093e266796391de4e5 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.c new file mode 100644 index 0000000000000000000000000000000000000000..58bf15a7071e2dbfbea0a799bfd5eebe2d9f8403 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/hmi_module.h new file mode 100644 index 0000000000000000000000000000000000000000..056f8d7310eb14335c256933e8d998bf09919cc6 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.c new file mode 100644 index 0000000000000000000000000000000000000000..56f0c0bb3fa394c355dcbef7f6387270bf31dd67 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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_WriteDMA(&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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..900a00d8065b0154f3883d213be12f63610d0be1 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c new file mode 100644 index 0000000000000000000000000000000000000000..df5e918648921817e0e0fd5c9d98c5c0ee6bcb26 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.c @@ -0,0 +1,184 @@ +/** + * @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) + +/* 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. + * @retval None. + */ +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; + uartFrame->rxAckFlag = 0; +} + +/** + * @brief Set Dma status. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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 Uart Dma interupt callback func. + * @param handle Uart handle. + * @retval None. + */ +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; + /* Received information answered, information update reserved. */ + if (g_uartFrame.rxAckFlag == 1) { + g_uartFrame.uartItTxFlag = 1; + g_uartFrame.rxAckFlag = 0; + } + 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 Read CallBack Function. + * @param handle Uart handle. + * @retval None. + */ +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. + * @retval None. + */ +void UartRecvInit(void) +{ + /* Uart reception initialization */ + FrameRecvClear(&g_uartFrame); + HAL_UART_ReadIT(&g_uart0, &g_uartFrame.rxData, 1); +} + +/** + * @brief Uart Read Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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.rxAckFlag = 1; + g_uartFrame.rxLen = 0; + } + } + g_uartFrame.frameFlag = 0; +} + +/** + * @brief Uart Write Data Process Function. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +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/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h new file mode 100644 index 0000000000000000000000000000000000000000..f1f8f89951fd2ab017f9ad6082a2542ca925aaaa --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_FOC/user/pmsm_sensorless_2shunt_foc/user_interface/uart_module.h @@ -0,0 +1,47 @@ +/** + * @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; + unsigned char rxAckFlag; +} 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/yibaina_3061M/GIM4310-10_Six_Step_Wave/readme.md b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..6af5e381d1d115306462173dbecc5d633d779bdd --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/readme.md @@ -0,0 +1,20 @@ +# GIM4310-10_Six_Step_Wave + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的反电动势采样的无感电机六步方波调速系统应用 + +**【环境要求】** + +- 所有单板电源改制为演示用的24V低压,电机选用GIM4310-10 +- 电机(黄绿蓝)相线分别对应功率板上U/V/W通道接口 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 点击开发板按键启动电机 + +- 开发板蓝色电位器,可以调节电机转动的快慢。(12-77HZ) \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/feature.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..d89f618cebf4b6cc562e1aba9980969794025b5b --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/feature.h @@ -0,0 +1,94 @@ +/** + * @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. + * @date 2025-04-23 15:45:47 + */ + +#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/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/main.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..8c5ceec43ee5c980f4cbe107ee89e2a19d56c3e0 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/main.h @@ -0,0 +1,84 @@ +/** + * @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. + * @date 2025-04-23 15:45:47 + */ + +/* 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 "crg.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 SYS_LED_PIN GPIO_PIN_3 +#define SYS_LED_HANDLE g_gpio2 +#define GpioStartStop_PIN GPIO_PIN_4 +#define GpioStartStop_HANDLE g_gpio2 + +extern ACMP_Handle g_acmp0; +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 GPIO_Handle g_gpio1; +extern GPIO_Handle g_gpio2; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void MotorStatemachineCallBack(void *handle); +void TIMER1_DMAOverFlow_InterruptProcess(void *handle); +void MotorCarrierProcessCallback(void *aptHandle); +void MotorSysErrCallback(void *aptHandle); + +void MotorStartStopKeyCallback(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/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/system_init.c b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..c737cc231282cc21188d9202e3e7e26c295523be --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/generatecode/system_init.c @@ -0,0 +1,530 @@ +/** + * @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. + * @date 2025-04-23 15:45:47 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_RATE 115200 + +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 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_ADCINA11; /* PIN9(ADC AIN11) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM5, &socParam); + + socParam.adcInput = ADC_CH_ADCINA12; /* PIN10(ADC AIN12) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_NUM2, &socParam); + + socParam.adcInput = ADC_CH_ADCINA10; /* PIN8(ADC AIN10) */ + socParam.sampleTotalTime = ADC_SOCSAMPLE_5CLK; /* adc sample total time 5 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_5CLK; /* adc sample total time 5 adc_clk */ + socParam.trigSource = ADC_TRIGSOC_SOFT; + socParam.continueMode = BASE_CFG_DISABLE; + socParam.finishMode = ADC_SOCFINISH_NONE; + HAL_ADC_ConfigureSoc(&g_adc0, ADC_SOC_NUM9, &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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt0.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt0.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt0.adcTrg.cntCmpSOCA = 6000; /* 6000 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_CMPA_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_CMPC_UP; + 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, 6); /* 6 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt1.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 is dead-band value */ + + /* ADC Trigger SOCA */ + g_apt1.adcTrg.trgEnSOCA = BASE_CFG_ENABLE; + g_apt1.adcTrg.cntCmpSOCA = 1; /* 1 is count compare point of ADC trigger source SOCA when using CMPA */ + g_apt1.adcTrg.trgSrcSOCA = APT_CS_SRC_CNTR_ZERO; + g_apt1.adcTrg.trgScaleSOCA = 1; + + g_apt1.adcTrg.cntCmpLoadMode = APT_BUFFER_INDEPENDENT_LOAD; + g_apt1.adcTrg.cntCmpLoadEvt = APT_COMPARE_LOAD_EVENT_ZERO; + + 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 = 6250; /* 6250 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 = 3125; /* 3125 is count compare point of the left edge of PWM waveform */ + g_apt2.waveform.cntCmpRightEdge = 3125; /* 3125 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 = 150; /* 150 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); +} + +static void GPIO_Init(void) +{ + 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(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_LOW_LEVEL); + HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_FALL_EDGE); + + HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, MotorStartStopKeyCallback); + IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); + IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ + IRQ_EnableN(IRQ_GPIO2); /* gpio interrupt enable */ + + return; +} + +__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 = ((float)HAL_CRG_GetIpFreq((void *)TIMER1) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 500; + + g_timer1.baseAddress = TIMER1; + g_timer1.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer1.bgLoad = (load < 1) ? 0 : (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, 2); /* 2 is priority value */ + IRQ_EnableN(IRQ_TIMER1); +} + +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} + +static void IOConfig(void) +{ + SYSCTRL0->SC_SYS_STAT.BIT.update_mode = 0; + SYSCTRL0->SC_SYS_STAT.BIT.update_mode_clear = 1; + /* Config PIN9 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_5_AS_ADC_AIN11); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_5_AS_ADC_AIN11, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_5_AS_ADC_AIN11, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_5_AS_ADC_AIN11, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_5_AS_ADC_AIN11, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN10 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_3_AS_ADC_AIN12); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_3_AS_ADC_AIN12, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_3_AS_ADC_AIN12, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_3_AS_ADC_AIN12, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_3_AS_ADC_AIN12, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN8 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO3_6_AS_ADC_AIN10); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO3_6_AS_ADC_AIN10, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO3_6_AS_ADC_AIN10, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO3_6_AS_ADC_AIN10, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO3_6_AS_ADC_AIN10, 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 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 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 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 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 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 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 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(); + UART0_Init(); + ACMP0_Init(); + APT0_Init(); + APT1_Init(); + APT2_Init(); + ADC0_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/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/main.c b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..83b0b133dc04b11a90886f0b8ed8be5f6d0463e3 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/main.c @@ -0,0 +1,67 @@ +/** + * @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. + * @date 2025-04-23 15:45:47 + */ + +#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; +TIMER_Handle g_timer1; +UART_Handle g_uart0; +APT_Handle g_apt0; +APT_Handle g_apt1; +APT_Handle g_apt2; +ADC_Handle g_adc0; +GPIO_Handle g_gpio1; +GPIO_Handle g_gpio2; +/* 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 diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..d53b28d7fc8d6aee8652ea6b32789754630ed946 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.c @@ -0,0 +1,562 @@ +/** + * @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 for ECBMCU201MPC board. + * @details BLDC six-step application based on the ECBMCU201MPC board + * 1) Motor model is Gimbal GBM2804H-100T. + * 2) Select the bldc six-step sensorless example in the sample column + of chipConfig and click Generate Code. + * 3) It's power supply must be changed to 12V. + */ + +#include "debug.h" +#include "mcs_assert.h" +#include "mcs_user_config.h" +#include "mcs_status.h" +#include "mcs_carrier.h" +#include "mcs_motor_process.h" + +/*------------------------------- Macro Definition -----------------------------------------------*/ +#define US_PER_MS 1000 +#define APT_FULL_DUTY 1.0f + +/* Motor control handle for bldc */ +static MtrCtrlHandle g_mc; + +static APT_RegStruct* g_aptCp[PHASE_MAX_NUM] = {BRIDGE_CTR_APT_U, BRIDGE_CTR_APT_V, BRIDGE_CTR_APT_W}; + +/** + * @brief Initialzer of system tick. + * @param mtrCtrl Motor control struct handle. + * @retval None. + */ +static void TimerTickInit(MtrCtrlHandle *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 Read the ADC current sampling value of the compressor. + * @param CurrUvw Three-phase current. + * @retval None. + */ +static void ReadBemfUVWMotor(UVWBemf *bemfUVW) +{ + MCS_ASSERT_PARAM(bemfUVW != NULL); + bemfUVW->u = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_U_SOC_NUM)&0xFFF); + bemfUVW->v = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_V_SOC_NUM)&0xFFF); + bemfUVW->w = (int)(HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_W_SOC_NUM)&0xFFF); +} + +/** + * @brief Init motor control task. + * @retval None. + */ +static void TSK_InitMotor(void) +{ + /* Initialize target speed. */ + g_mc.spdCmdHz = SDP_TARGET_VALUE; + /* zeroPoint = IN_VOLTAGE_BUS / 2.0; 4095/3.3 :ADC value corresponding to 1 V */ + g_mc.zeroPoint = ((((float)IN_VOLTAGE_BUS / 2.0) * VOL_DIVIDER_COEFFICIENT) * 4095 / 3.3); + g_mc.pwmDuty = FORCE_DRAG_MINDUTY; + + /* Sets the number of sample filtering times for zero-crossing sampling. */ + g_mc.sysVar.bemfFilterCnt = FILTER_COUNT; + g_mc.sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + + g_mc.stateMachine = FSM_IDLE; + g_mc.aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Speed management initialization. */ + RMG_Init(&g_mc.spdRmg, CTRL_SYSTICK_PERIOD, USER_SPD_SLOPE); /* Init speed slope */ + TimerTickInit(&g_mc); + + /* Pid control parameter initialization. */ + g_mc.spdPi.kp = SPD_PID_KP; + g_mc.spdPi.ki = SPD_PID_KI; + g_mc.spdPi.ts = SPD_PID_TS; + g_mc.spdPi.upperLimit = APT_DUTYLIMIT_MAX; + g_mc.spdPi.lowerLimit = APT_DUTYLIMIT_MIN; + + /* BLDC six-step control initialization. */ + g_mc.stepCtrl.phaseStep = STEP1; + g_mc.stepCtrl.controlApt.u = &g_apt0; + g_mc.stepCtrl.controlApt.v = &g_apt1; + g_mc.stepCtrl.controlApt.w = &g_apt2; +} + + +/** + * @brief Software Initialization. + * @retval None. + */ +static void InitSoftware(void) +{ + TSK_InitMotor(); + + g_mc.readBemfUVW = ReadBemfUVWMotor; +} + +/** + * @brief Enable three-phase pwm output. + * @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 = 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 = 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 Force rotor alignment to home position. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceAlign(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + MotorPwmOutputEnable(g_aptCp); + mtrCtrl->stepCtrl.phaseStep = STEP6; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->stepCtrl.phaseStep = STEP1; + SixStepPwm(&mtrCtrl->stepCtrl); + BASE_FUNC_DELAY_MS(100); /* Delay 100 ms waiting for rotor alignment. */ + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); +} + +/** + * @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_WAIT_STOP; + } +} + +/** + * @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 int maxDutyCnt) +{ + MCS_ASSERT_PARAM(aptAddr != NULL); + MCS_ASSERT_PARAM(maxDutyCnt != 0); + unsigned int dutyCnt; + dutyCnt = maxDutyCnt * APT_FULL_DUTY; + /* Open the three-phase lower pipe */ + for (unsigned int i = 0; i < PHASE_MAX_NUM; i++) { + APT_RegStruct *aptx = aptAddr[i]; + aptx->TC_REFC.BIT.rg_cnt_refc = dutyCnt; + aptx->TC_REFD.BIT.rg_cnt_refd = dutyCnt; + } +} + +/** + * @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(MtrCtrlHandle *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 Clear historical values of all controller before start-up. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ClearBeforeStartup(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->aptMaxcntCmp = g_apt0.waveform.timerPeriod; + + /* Clear bemf parameters. */ + mtrCtrl->bemf.u = 0; + mtrCtrl->bemf.v = 0; + mtrCtrl->bemf.w = 0; + + /* Clear tickcnt. */ + mtrCtrl->msTickCnt = 0; + + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + + /* Clear spd parameters. */ + mtrCtrl->spdEstHz = 0; + mtrCtrl->spdRefHz = 0; + + mtrCtrl->stepCtrl.phaseStep = STEP1; + + mtrCtrl->sysTickCnt = 0; + + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_START_INTERVAL; + mtrCtrl->sysVar.changePhaseFlag = 0; + mtrCtrl->sysVar.firstEventFilterFlag = 0; + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 0; + for (int i = 0; i < STEP_MAX_NUM; i++) { + mtrCtrl->sysVar.stepTime[i] = 0; + } + /* RMG CLEAR */ + RMG_Clear(&mtrCtrl->spdRmg); /* Clear the history value of speed slope control */ + /* SPDCTRL CLEAR */ + PID_Clear(&mtrCtrl->spdPi); +} + +/** + * @brief Check bootstrap capacitor charge time. + * @param mtrCtrl The motor control handle. + * @param stateMachine Motor Control Status. + * @retval None. + */ +static void CheckBootstrpCapChargeTime(MtrCtrlHandle *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) { + /* Update Status. */ + *stateMachine = FSM_CLEAR; + } +} + +/** + * @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 Deceleration control phase before stop. + * @param mtrCtrl The motor control handle. + * @param statusReg Motor Control Status. + * @param targetSpd Deceleration target value. + * @param switchSpd Switch to stop state speed. + * @retval None. + */ +static void DecelerateSpeed(MtrCtrlHandle *mtrCtrl, FsmState *stateMachine, float targetSpd, float switchSpd) +{ + /* Reduce speed before stop. */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, targetSpd); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + if (mtrCtrl->spdRefHz <= switchSpd) { /* Maximum speed for switching to the FSM_STOP state */ + *stateMachine = FSM_STOP; + } +} + +/** + * @brief System timer tick task. + * @param mtrCtrl The motor control handle. + * @param aptAddr Three-phase APT address pointer. + * @retval None. + */ +static void TSK_SystickIsr(MtrCtrlHandle *mtrCtrl, APT_RegStruct **aptAddr) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(aptAddr != NULL); + SysStatusReg *statusReg = &mtrCtrl->statusReg; + volatile FsmState *stateMachine = &mtrCtrl->stateMachine; + mtrCtrl->msTickCnt++; + /* Pre-processing of motor status. */ + MotorStatePerProc(statusReg, stateMachine); + /* statemachine */ + switch (*stateMachine) { + case FSM_IDLE: + CheckSysCmdStart(mtrCtrl, aptAddr, statusReg, (FsmState *)stateMachine); + break; + case FSM_CAP_CHARGE: + /* Bootstrap Capacitor Charging Timing */ + CheckBootstrpCapChargeTime(mtrCtrl, (FsmState *)stateMachine); + break; + case FSM_CLEAR: + /* Clearing control parameters. */ + ClearBeforeStartup(mtrCtrl); + /* Rotor alignment. */ + ForceAlign(mtrCtrl); + *stateMachine = FSM_STARTUP; + break; + case FSM_STARTUP: + /* Forced drag. */ + break; + case FSM_RUN: + /* Speed ramp control */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + mtrCtrl->spdPi.error = mtrCtrl->spdRefHz - mtrCtrl->spdEstHz; + /* Speed loop control */ + mtrCtrl->pwmDuty = PI_Exec(&mtrCtrl->spdPi); + break; + case FSM_WAIT_STOP: + /* 5.0f : maximum speed for switching to the FSM_STOP state */ + DecelerateSpeed(mtrCtrl, (FsmState *)stateMachine, 0.0f, 5.0f); + break; + case FSM_STOP: + MotorPwmOutputDisable(aptAddr); + SysRunningClr(statusReg); + *stateMachine = FSM_IDLE; + break; + case FSM_FAULT: + /* Overcurrent state */ + CheckOverCurrentState(statusReg, (FsmState *)stateMachine); + break; + default: + break; + } +} + +/** + * @brief Overcurrent protection. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorSysErrCallback(void *aptHandle) +{ + /* Overcurrent protection callback function. */ + BASE_FUNC_UNUSED(aptHandle); + MotorPwmOutputDisable(g_aptCp); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_U], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_V], APT_OC_COMBINE_EVENT_A1); + DCL_APT_ClearOutCtrlEventFlag((APT_RegStruct *)g_aptCp[PHASE_W], APT_OC_COMBINE_EVENT_A1); + /* Status setting error */ + SysErrorSet(&g_mc.statusReg); + DBG_PRINTF("APT error! \r\n"); + HAL_GPIO_SetValue(&g_gpio2, GPIO_PIN_3, GPIO_LOW_LEVEL); +} + +/** + * @brief Motor blockage protection function. + * @retval None. + */ +static void MotorBlockageProtect(void) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= g_mc.sysVar.lastZeroPoint) + ? currentTick - g_mc.sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - g_mc.sysVar.lastZeroPoint + currentTick + 1; + if (intervalTick > SYSTICK_GetCRGHZ()) { + MotorPwmOutputDisable(g_aptCp); + SysErrorSet(&g_mc.statusReg); + g_mc.spdEstHz = 0; + return; + } +} + +/** + * @brief Carrier Interruption. + * @param aptHandle The apt Handle. + * @retval None. + */ +void MotorCarrierProcessCallback(void *aptHandle) +{ + BASE_FUNC_UNUSED(aptHandle); + /* USER CODE BEGIN APT0_TIMER_INTERRUPT */ + MCS_CarrierProcess(&g_mc); + if (g_mc.stateMachine == FSM_RUN || g_mc.stateMachine == FSM_WAIT_STOP) { + MotorBlockageProtect(); + } + /* USER CODE END APT0_TIMER_INTERRUPT */ +} + +/** + * @brief Change phase delay callback function. + * @param handle The TIMER1 Handle. + * @retval None. + */ +void MotorStatemachineCallBack(void *handle) +{ + /* TIMER1CallbackFunction */ + BASE_FUNC_UNUSED(handle); + TSK_SystickIsr(&g_mc, g_aptCp); +} + +/** + * @brief Check Potentiometer Value and adjust speed. + * @param None. + * @retval None. + */ +static void AdjustSpeedFunction(void) +{ + static unsigned int potentiomitorAdcValue = 0; + static float spdCmdHz = 0; + static float spdCmdHzLast = SDP_MAX_VALUE; + HAL_ADC_SoftTrigSample(&ADC_HANDLE, ADC_SOC_NUM9); /* Get the speed adjustment resistance. */ + potentiomitorAdcValue = HAL_ADC_GetConvResult(&ADC_HANDLE, ADC_SOC_NUM9); + /* 4045.0 is adc sample max value of potentiomitor */ + spdCmdHz = (float)potentiomitorAdcValue / 4045.0 * SDP_MAX_VALUE; + if (spdCmdHz < SDP_MIN_VALUE) { /* Speed protection. */ + spdCmdHz = SDP_MIN_VALUE; + } + if (spdCmdHz > SDP_MAX_VALUE) { + spdCmdHz = SDP_MAX_VALUE; + } + float delta = spdCmdHzLast > spdCmdHz ? (spdCmdHzLast - spdCmdHz) : (spdCmdHz - spdCmdHzLast); + /* 1.0 : If the speed fluctuation is less than 1.0Hz, no change is made. */ + if (delta < 1.0) { + return; + } + spdCmdHzLast = spdCmdHz; + g_mc.spdCmdHz = spdCmdHz; +} + +/** + * @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 (SysIsRunning(&g_mc.statusReg)) { /* stop apt output, motor is off status */ + SysCmdStopSet(&g_mc.statusReg); + } else { /* start apt output, motor is on status */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + SysCmdStartSet(&g_mc.statusReg); + } + } +} + +/** + * @brief User application entry. + * @retval BSP_OK. + */ +int MotorMainProcess(void) +{ + SystemInit(); + /* System Initialization. */ + unsigned int tickNum100Ms = 200; /* 100ms tick */ + static unsigned int tickCnt100Ms = 0; + unsigned int tickNum500Ms = 1000; /* 500ms tick */ + static unsigned int tickCnt500Ms = 0; + + HAL_TIMER_Start(&g_timer1); + /* Disable PWM output before startup. */ + MotorPwmOutputDisable(g_aptCp); + InitSoftware(); + /* Start the PWM clock. */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); + + while (true) { + if (g_mc.msTickCnt - tickCnt100Ms >= tickNum100Ms) { + tickCnt100Ms = g_mc.msTickCnt; + /* User Code 100ms Event */ + AdjustSpeedFunction(); + } + if (g_mc.msTickCnt - tickCnt500Ms >= tickNum500Ms) { + if (SysIsError(&g_mc.statusReg) == true) { + break; + } + /* The LED blinks when no status is not error. */ + HAL_GPIO_TogglePin(&SYS_LED_HANDLE, SYS_LED_PIN); + tickCnt500Ms = g_mc.msTickCnt; + } + } + return 0; +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..a2fdeb2c62a9185aa9d9d08c3408e0e88486066c --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_motor_process.h @@ -0,0 +1,47 @@ +/** + * @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 ECBMCU201MPC board. + */ +#ifndef McuMagicTag_MCS_MOTOR_PROCESS_H +#define McuMagicTag_MCS_MOTOR_PROCESS_H + +#include "main.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/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..6f88c4c45d21c4b4612677b5d176abd47457bd2f --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/application/mcs_user_config.h @@ -0,0 +1,94 @@ +/** + * @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_config.h + * @author MCU Algorithm Team + * @brief This file provides config macros for ECBMCU201MPC app. + */ +#ifndef McuMagicTag_MCS_CONFIG_H +#define McuMagicTag_MCS_CONFIG_H + +#if defined(CHIP_3061MNPICA) || defined(CHIP_3061MNNICA) || defined(CHIP_3061MNPIC8) || defined(CHIP_3061MNNIC8) +#define ADC_U_SOC_NUM ADC_SOC_NUM2 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM6 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 +#define ADC_HANDLE g_adc0 +#endif + +#if defined (CHIP_3066MNPIRH) || defined (CHIP_3065PNPIRH) || defined (CHIP_3065PNPIRE) || defined (CHIP_3065PNPIRA) +#define ADC_U_SOC_NUM ADC_SOC_NUM3 +#define ADC_V_SOC_NUM ADC_SOC_NUM5 +#define ADC_W_SOC_NUM ADC_SOC_NUM7 +#define ADC_SPD_ADJ_SOC_NUM ADC_SOC_NUM9 + +#define ADC_HANDLE g_adc2 +#endif + +#define APT_PWM_FREQ 12000 /* PWM frequency 12K Hz. */ +#define CTRL_CURR_PERIOD (1.0f / APT_PWM_FREQ) /* carrier ISR period (S) */ +#define CTRL_CURE_PERIOD_US 83 + +#define SYSTICK_PERIOD_US 500u /* systick period. unit : us */ + +#define INV_CAP_CHARGE_MS 3u /* Bootstrap capacitor charge time. unit : ms */ + +#define CTRL_SYSTICK_PERIOD 0.0005f /* systick control period, 500us */ + +#define USER_SPD_SLOPE 60.0f /* slope of velocity change */ + +#define IN_VOLTAGE_BUS 24 /* Motor input voltage */ +#define POLES 14 /* logarithm of motor pole */ +#define MATH_PI 3.14 /* Pi */ +#define MOTOR_K 0.66 /* Torque Coefficient */ + +#define RAMP_STP 60 /* Slope of forced draging acceleration */ +#define RAMP_DUTY_PWM 0.5 /* 1.0% */ + +#define FORCE_DRAG_MINDUTY 10 /* APT minimum duty cycle during forced drag */ +#define FORCE_DRAG_MAXDUTY 15 /* APT maximum duty cycle during forced drag */ + +#define DRAG_START_INTERVAL 1000 /* Force drag change phase time */ +#define DRAG_STOP_INTERVAL 400 /* Force drag change phase time */ + +/* Parameters of the motor in the RUN */ +#define FILTER_COUNT 3 /* Filter Times */ +#define PHASE_OFFSET 9000 /* Phase delay due to filtering */ + +#define APT_DUTYLIMIT_MAX 99.9 /* Maximum duty cycle of the output APT */ +#define APT_DUTYLIMIT_MIN 8.0 /* Minimum duty cycle of the output APT */ + +#define BRIDGE_CTR_APT_U APT0 /* APT address that controls the U phase */ +#define BRIDGE_CTR_APT_V APT1 /* APT address that controls the V phase */ +#define BRIDGE_CTR_APT_W APT2 /* APT address that controls the W phase */ + +#define SDP_MAX_VALUE 77.00 /* Maximum change phase frequency */ +#define SDP_MIN_VALUE 12.0 /* Minimum change phase frequency */ +#define SDP_TARGET_VALUE 77.00 /* Target change phase frequency */ + +/* SPD PID Param */ +#define SPD_PID_KP 0.05 /* P parameter of PID control */ +#define SPD_PID_KI 6 /* I parameter of PID control */ +#define SPD_PID_TS 0.0005 /* TS parameter of PID control cycle */ + +#define OP_TO_CL_INTERGRAL 8.0 /* Open-loop switching closed-loop integral term to prevent sudden current change. */ + +#define VOL_DIVIDER_COEFFICIENT 0.09091f /* Division coefficient of the zero-crossing detection sampling circuit */ + +#define SPD_FILTER_FC 30 + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..7779fbef2e3eee99fb209f617bb4d3f7d923309d --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.c @@ -0,0 +1,224 @@ +/** + * @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_user_config.h" +#include "mcs_assert.h" +#include "debug.h" + +#define S_TO_US 1000000 +#define S_TO_SYSTICK 100000000 + +/** + * @brief Sets the duty cycle of the H-bridge APT. + * @param aptHandle APT module handle. + * @param duty PWM duty. Range: 0.1 ~ 99.9. + * @retval None. + */ +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + MCS_ASSERT_PARAM(duty > 0); + /* Set pwm duty of uvw pahse */ + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.u, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.v, duty); + HAL_APT_SetPWMDutyByNumber(mtrCtrl->stepCtrl.controlApt.w, duty); +} + +/** + * @brief Strong drag start. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ForceDragAcc(MtrCtrlHandle *mtrCtrl) +{ + /* Verifying Parameters. */ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + unsigned int voltageDValue; + unsigned int dragChangeFreq; + unsigned int timerperiod; + unsigned int freqLast; + unsigned int aptCountsOneUs; + + mtrCtrl->sysVar.accTimeCnt++; + if (mtrCtrl->sysVar.accTimeCnt < mtrCtrl->sysVar.dragChangePhaseTime) { + return; + } + + mtrCtrl->sysVar.accTimeCnt = 0; + /* Step 1: Calculate the voltage difference. */ + voltageDValue = IN_VOLTAGE_BUS * RAMP_DUTY_PWM; + /* Step 2: Calculate the commutation frequency. */ + freqLast = S_TO_US / (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US); + dragChangeFreq = voltageDValue * STEP_MAX_NUM * POLES / (MOTOR_K * 2 * MATH_PI) + freqLast; /* 2*PI = 360° */ + /* Step 3: Convert the commutation frequency to the commutation count value. */ + timerperiod = mtrCtrl->stepCtrl.controlApt.u->waveform.timerPeriod * CTRL_CURE_PERIOD_US; + mtrCtrl->sysVar.dragChangePhaseTime = S_TO_US / (timerperiod * dragChangeFreq); + + /* Determine whether the change phase speed has reached the speed of stopping forced drag. */ + if (mtrCtrl->sysVar.dragChangePhaseTime < DRAG_STOP_INTERVAL) { + mtrCtrl->sysVar.dragChangePhaseTime = DRAG_STOP_INTERVAL; + mtrCtrl->sysVar.accTimeCnt = 0; + mtrCtrl->sysVar.bemfFilterCnt = 0; + mtrCtrl->stateMachine = FSM_RUN; + mtrCtrl->sysVar.lastZeroPoint = DCL_SYSTICK_GetTick(); + mtrCtrl->spdPi.integral = OP_TO_CL_INTERGRAL; + } + + /* Shorten the time interval of forced drag change phase. */ + mtrCtrl->pwmDuty += RAMP_DUTY_PWM; + aptCountsOneUs = HAL_CRG_GetIpFreq(APT0_BASE) / S_TO_US; + mtrCtrl->sysVar.waitTime = (mtrCtrl->sysVar.dragChangePhaseTime * CTRL_CURE_PERIOD_US * aptCountsOneUs) >> 1; + /* Change phase time is 2 the waiting time. */ + mtrCtrl->spdRefHz = (float)(HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime * 2)) / STEP_MAX_NUM; + mtrCtrl->spdEstHz = mtrCtrl->spdRefHz; + mtrCtrl->spdRmg.yLast = mtrCtrl->spdRefHz; + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + /* Limiting the PWM Duty Cycle Range. */ + if (mtrCtrl->pwmDuty > FORCE_DRAG_MAXDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MAXDUTY; + } + if (mtrCtrl->pwmDuty < FORCE_DRAG_MINDUTY) { + mtrCtrl->pwmDuty = FORCE_DRAG_MINDUTY; + } + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); +} + +/** + * @brief Zero-crossing filter. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroSampleFilter(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + mtrCtrl->sysVar.bemfFilterCnt++; + /* Filter the number of samples. */ + if (mtrCtrl->sysVar.bemfFilterCnt >= FILTER_COUNT) { + mtrCtrl->sysVar.bemfFilterCnt = 0; + unsigned int currentTick = DCL_SYSTICK_GetTick(); + if (mtrCtrl->sysVar.firstEventFilterFlag == 0) { + mtrCtrl->sysVar.lastZeroPoint = currentTick; + mtrCtrl->sysVar.changePhaseFlag = 1; + mtrCtrl->sysVar.firstEventFilterFlag = 1; + return; + } + /* Calculate the time interval between the last zero crossing. */ + mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] = currentTick >= mtrCtrl->sysVar.lastZeroPoint + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + mtrCtrl->sysVar.stepTimeNum++; + /* Wait time is half the interval. */ + mtrCtrl->sysVar.waitTime = mtrCtrl->sysVar.stepTime[mtrCtrl->stepCtrl.phaseStep] >> 1; + mtrCtrl->sysVar.waitTime -= PHASE_OFFSET; + mtrCtrl->sysVar.lastZeroPoint = currentTick; + /* Update flag. */ + mtrCtrl->sysVar.changePhaseFlag = 1; + } +} + +/** + * @brief Back EMF zero crossing check. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void BemfZeroCheck(MtrCtrlHandle *mtrCtrl) +{ + /* The step corresponds to different conditional judgments. */ + unsigned int bemfCheckTable[STEP_MAX_NUM] = {mtrCtrl->bemf.w < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.w > mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.v < mtrCtrl->zeroPoint ? 1 : 0, + mtrCtrl->bemf.u > mtrCtrl->zeroPoint ? 1 : 0}; + + if (bemfCheckTable[mtrCtrl->stepCtrl.phaseStep] == 1) { + BemfZeroSampleFilter(mtrCtrl); + } +} + +/** + * @brief Change phase and speed estimation. + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void ChangePhase(MtrCtrlHandle *mtrCtrl) +{ + unsigned int currentTick = DCL_SYSTICK_GetTick(); /* Get the current tick value. */ + unsigned int intervalTick = (currentTick >= mtrCtrl->sysVar.lastZeroPoint) + ? currentTick - mtrCtrl->sysVar.lastZeroPoint + : SYSTICK_MAX_VALUE - mtrCtrl->sysVar.lastZeroPoint + currentTick + 1; + /* Start average filtering when the number of recorded data reaches six. */ + if (mtrCtrl->sysVar.stepTimeNum >= STEP_MAX_NUM) { + mtrCtrl->sysVar.stepTimeNum = 0; + mtrCtrl->sysVar.stepTimeFilterEnable = 1; + } + /* If the accumulated time is greater than the waiting commutation time, commutation is performed. */ + if (intervalTick > mtrCtrl->sysVar.waitTime) { + if (mtrCtrl->sysVar.stepTimeFilterEnable) { /* 6-step commutation time averaging if filtering is enabled. */ + unsigned int totalTime = mtrCtrl->sysVar.stepTime[STEP1] + mtrCtrl->sysVar.stepTime[STEP2] + + mtrCtrl->sysVar.stepTime[STEP3] + mtrCtrl->sysVar.stepTime[STEP4] + + mtrCtrl->sysVar.stepTime[STEP5] + mtrCtrl->sysVar.stepTime[STEP6]; + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / totalTime; + } else { + mtrCtrl->spdEstHz = (float)HAL_CRG_GetIpFreq(SYSTICK_BASE) / (mtrCtrl->sysVar.waitTime << 1) / STEP_MAX_NUM; + } + /* Change phase. */ + mtrCtrl->stepCtrl.phaseStep = (mtrCtrl->stepCtrl.phaseStep + 1) % STEP_MAX_NUM; + SixStepPwm(&mtrCtrl->stepCtrl); + mtrCtrl->sysVar.changePhaseFlag = 0; + } +} + +/** + * @brief Zero-crossing detection and change phase + * @param mtrCtrl The motor control handle. + * @retval None. + */ +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + /* Offset value of the calibration value of the three-phase current */ + + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + ForceDragAcc(mtrCtrl); /* Forced drag. */ + break; + + case FSM_RUN: + case FSM_WAIT_STOP: + mtrCtrl->readBemfUVW(&mtrCtrl->bemf); + MCS_SetCtrAptDuty(mtrCtrl, mtrCtrl->pwmDuty); + if (mtrCtrl->sysVar.changePhaseFlag) { + /* Change phase process. */ + ChangePhase(mtrCtrl); + } else { + /* Zero-crossing detection procedure. */ + BemfZeroCheck(mtrCtrl); + } + break; + + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..05fc26667e96b59288aba49344f448a3bf243816 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_carrier.h @@ -0,0 +1,91 @@ +/** + * @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_six_step.h" +#include "mcs_ramp_mgmt.h" +#include "mcs_spd_ctrl.h" +#include "mcs_fsm.h" + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + unsigned int u; /**< Component u of the three-phase static coordinate frame variable. */ + unsigned int v; /**< Component v of the three-phase static coordinate frame variable. */ + unsigned int w; /**< Component w of the three-phase static coordinate frame variable. */ +} UVWBemf; + +typedef void (*ReadBemf)(UVWBemf *bemfUVW); + +/** + * @brief The definition of the systematic global variables + */ +typedef struct { + unsigned char changePhaseFlag; /**< Flag indicating that delay change phase is required */ + unsigned char firstEventFilterFlag; /**< First zero-crossing event filtering flag. */ + unsigned int dragChangePhaseTime; /**< Interval for forced drag acceleration */ + unsigned int accTimeCnt; /**< Acceleration time count */ + + unsigned int bemfFilterCnt; /**< Number of sample filtering times for zero-crossing detection. */ + + unsigned int lastZeroPoint; /**< Time of the last zero point */ + unsigned int waitTime; /**< Time to wait for change phase */ + unsigned int stepTime[STEP_MAX_NUM]; /**< Record the time spent on each step */ + unsigned int stepTimeNum; /**< Number of data records in the steptime array. */ + unsigned int stepTimeFilterEnable; +} SysVariable; + +typedef struct { + volatile float spdCmdHz; /**< Set target change phase frequency */ + float spdRefHz; /**< Command values after speed ramp management */ + float spdEstHz; /**< Actual change phase frequency of feedback */ + float pwmDuty; /**< APT duty cycle */ + unsigned int zeroPoint; /**< Adc value of zero point */ + + unsigned short aptMaxcntCmp; /**< Apt Maximum Comparison Count */ + + unsigned short sysTickCnt; /**< System Timer Tick Count */ + unsigned short capChargeTickNum; /**< Bootstrap Capacitor Charge Tick Count */ + unsigned short msTickNum; /**< Number of ticks corresponding to 1 ms */ + volatile unsigned int msTickCnt; /**< Millisecond-level counter, which can be used in 1-ms and 5-ms tasks. */ + + RMG_Handle spdRmg; /**< Ramp management struct for the speed controller input reference */ + PID_Handle spdPi; /**< PI controller struct in the speed controller. */ + + UVWBemf bemf; /**< Three-phase back electromotive force */ + SixStepHandle stepCtrl; /**< Control structure of six-step square wave */ + + SysVariable sysVar; /**< System Variables */ + SysStatusReg statusReg; /**< System Status */ + FsmState stateMachine; /**< BLDC Motor Control State Machine */ + + ReadBemf readBemfUVW; /**< Function interface for obtaining the three-phase electromotive force */ +} MtrCtrlHandle; + +void MCS_CarrierProcess(MtrCtrlHandle *mtrCtrl); + +void MCS_SetCtrAptDuty(MtrCtrlHandle *mtrCtrl, unsigned int duty); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h new file mode 100644 index 0000000000000000000000000000000000000000..b3c79ea2c8fccfc6f797d664899b8a249118aa3d --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/common/mcs_fsm.h @@ -0,0 +1,55 @@ +/** + * @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_fsm.h + * @author MCU Algorithm Team + * @brief This file provides the definition of finite statemachine (FSM). + */ + +#ifndef McuMagicTag_MCS_FSM_H +#define McuMagicTag_MCS_FSM_H + +/** + * @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; + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c new file mode 100644 index 0000000000000000000000000000000000000000..c86e609c8e3512ec0e0569c06aae5f38afff8ebe --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.c @@ -0,0 +1,126 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief This file provides functions to control the H bridge. + */ + +#include "mcs_assert.h" +#include "mcs_six_step.h" + +/* Mode for disabling or enabling software-based forced output */ +#define APT_PWM_MODE 0 +#define APT_FRC_MODE 1 + +#define PWM_SIGNAL 1 + +#define FRC_LOW APT_OUT_CTRL_ACTION_LOW +#define FRC_HIGH APT_OUT_CTRL_ACTION_HIGH + +/** + * @brief Force PWM output by APT + * @param APTx The APT to use + * @param PwmAout Force to be high or low + * @param PwmAenble PWMA signal software force mode + * @param PwmBout Force to be high or low + * @param PwmBenble PWMB signal software force mode + */ +static void APT_ForcePwmByApt(APT_RegStruct *aptx, APT_Act actMode) +{ + MCS_ASSERT_PARAM(aptx != NULL); + switch (actMode) { + case APT_CHA_PWM_CHB_LOW: + /* Channel A: 0 means not force output enable, channel A output PWM. */ + DCL_APT_DisableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + /* Channel B: 2 means channel B force output LOW due to the A_H_B_L invert. */ + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_HIGH: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 2 means channel B force output HIGH. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_HIGH); + break; + case APT_CHA_LOW_CHB_LOW: + /* Channel A: 1 means force output enable. */ + /* Channel A: 1 means channel A force output LOW. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_A); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_A, APT_PWM_CONTINUOUS_ACTION_LOW); + /* Channel B: 1 means force output enable. */ + /* Channel B: 1 means channel A force output HIGH due to the A_H_B_L invert. */ + DCL_APT_EnableSwContPWMAction(aptx, APT_PWM_CHANNEL_B); + DCL_APT_SetSwContPWMAction(aptx, APT_PWM_CHANNEL_B, APT_PWM_CONTINUOUS_ACTION_LOW); + break; + default: + break; + } +} + +/** + * @brief Output six-step square wave. + * @param handle The SixStepHandle. + * @retval None. + */ +void SixStepPwm(const SixStepHandle *handle) +{ + MCS_ASSERT_PARAM(handle != NULL); + APT_RegStruct *aptU = handle->controlApt.u->baseAddress; /* Get apt u\v\w baseaddress. */ + APT_RegStruct *aptV = handle->controlApt.v->baseAddress; + APT_RegStruct *aptW = handle->controlApt.w->baseAddress; + switch (handle->phaseStep) { + case STEP1: /* U+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP2: /* U+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP3: /* V+, W- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_LOW); + break; + case STEP4: /* V+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_PWM_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_LOW_CHB_HIGH); + break; + case STEP5: /* W+, U- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + case STEP6: /* W+, V- */ + APT_ForcePwmByApt(aptU, APT_CHA_LOW_CHB_HIGH); + APT_ForcePwmByApt(aptV, APT_CHA_LOW_CHB_LOW); + APT_ForcePwmByApt(aptW, APT_CHA_PWM_CHB_LOW); + break; + default: + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h new file mode 100644 index 0000000000000000000000000000000000000000..08198c4caedc927239402496adfd0b3fb18df415 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_six_step.h @@ -0,0 +1,79 @@ +/** + * @ 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_six_step.c + * @author MCU Algorithm Team + * @brief The header file contains the following declaration: + * + StepEnum enum definition. + * + PhaseEnum enum definition. + * + UVW_AptReg structure definition. + * + SixStepHandle handle structure definition. + * + AptOutCombination structure definition. + * + Six Step Pwm Function And Six Step Pwm Overlap Function. + */ + +#ifndef MCS_SIX_STEP_H +#define MCS_SIX_STEP_H + +#include "apt.h" + +typedef enum { + STEP1 = 0, + STEP2, + STEP3, + STEP4, + STEP5, + STEP6, + STEP_MAX_NUM +} StepEnum; + +typedef enum { + U = 0, + V, + W, + PHASE_MAX_NUMS +} PhaseEnum; + +typedef enum { + APT_CHA_PWM_CHB_LOW, + APT_CHA_LOW_CHB_HIGH, + APT_CHA_LOW_CHB_LOW +} APT_Act; + +/** + * @brief Three-phase static coordinate frame variable. + */ +typedef struct { + APT_Handle *u; /**< Apt handle for controlling phase U. */ + APT_Handle *v; /**< Apt handle for controlling phase V. */ + APT_Handle *w; /**< Apt handle for controlling phase W. */ +} UVW_AptReg; + +typedef struct { + unsigned char phaseStep; /* Current step. */ + UVW_AptReg controlApt; /* Apt handles for controlling H bridge. */ +} SixStepHandle; + +typedef struct { + unsigned int upperout; /* High tube level */ + unsigned int upperstate; /* High tube state */ + unsigned int lowerout; /* Low tube level */ + unsigned int lowerstate; /* Low tube state */ +} AptOutCombination; + +void SixStepPwm(const SixStepHandle *handle); +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..d92ed312ac27deafb879eb892affc89d6cf35728 --- /dev/null +++ b/vendor/yibaina_3061M/GIM4310-10_Six_Step_Wave/user/mcs_sensorless_bldc_six_step_wave/func/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 \ No newline at end of file diff --git a/vendor/yibaina_3061M/Infrared_Receiver_sample/readme.md b/vendor/yibaina_3061M/Infrared_Receiver_sample/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4562cb9ae12122baa414167bb25ec5f2e1f8101a --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/readme.md @@ -0,0 +1,42 @@ +# Infrared_Receiver_sample + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的红外接收案例 + +**【环境要求】** + +- VS1838红外接收模块,购买链接 https://e.tb.cn/h.6oqK2NgbKIlLU5y?tk=ICVqVgHrBEB +- 接线方式: + + S---GPIO2_2---J2_15 + + 3.3v ---J1_15 + + GND---J1_7 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 打开串口,用配套的遥控发射红外或者用手机红外遥控发射对应码值。 + +KEY_OK = 28, +KEY_UP =24, +KEY_DOWN = 82 +KEY_LEFT = 8, +KEY_RIGHT =90, +KEY_1 = 69, +KEY_2 = 70, +KEY_3 = 71, +KEY_4 = 68, +KEY_5 = 64, +KEY_6 = 67, +KEY_7 = 7, +KEY_8 = 21, +KEY_9 =9, +KEY_0 = 25, +KEY_*=22 +KEY_# =13 diff --git a/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/feature.h b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..8831ce2a8a354a2f9f050cd5d3dddd41257cd7d1 --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/feature.h @@ -0,0 +1,120 @@ +/** + * @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. + * @date 2025-04-25 10:40:20 + */ + +#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. */ + +#define MCS_PARAM_CHECK MACRO_ENABLE +#define APT_PARAM_CHECK MACRO_ENABLE +#define ADC_PARAM_CHECK MACRO_ENABLE +#define CAPM_PARAM_CHECK MACRO_ENABLE +#define CRG_PARAM_CHECK MACRO_ENABLE +#define I2C_PARAM_CHECK MACRO_ENABLE +#define UART_PARAM_CHECK MACRO_ENABLE +#define SPI_PARAM_CHECK MACRO_ENABLE +#define TIMER_PARAM_CHECK MACRO_ENABLE +#define IWDG_PARAM_CHECK MACRO_ENABLE +#define WWDG_PARAM_CHECK MACRO_ENABLE +#define GPIO_PARAM_CHECK MACRO_ENABLE +#define GPT_PARAM_CHECK MACRO_ENABLE +#define DMA_PARAM_CHECK MACRO_ENABLE +#define CRC_PARAM_CHECK MACRO_ENABLE +#define CFD_PARAM_CHECK MACRO_ENABLE +#define CMM_PARAM_CHECK MACRO_ENABLE +#define CAN_PARAM_CHECK MACRO_ENABLE +#define FLASH_PARAM_CHECK MACRO_ENABLE +#define PMC_PARAM_CHECK MACRO_ENABLE +#define ACMP_PARAM_CHECK MACRO_ENABLE +#define DAC_PARAM_CHECK MACRO_ENABLE +#define PGA_PARAM_CHECK MACRO_ENABLE +#define IOCMG_PARAM_CHECK MACRO_ENABLE +#define QDM_PARAM_CHECK MACRO_ENABLE + +/* 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/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.c b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.c new file mode 100644 index 0000000000000000000000000000000000000000..7eaae94e621ea2b8e7b6c15170d0e87554689745 --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.c @@ -0,0 +1,297 @@ +#include "ifd.h" +#include "debug.h" +#include "main.h" +#include "string.h" +#define RESET 0 +#define SET 1 + +#define IR_IN HAL_GPIO_GetPinValue(&g_gpio2, GPIO_PIN_2) // PA1 红外接收DQ引脚 +unsigned char ir_code[4]; // 解码值保存变量 +unsigned char ir_decode_ok_flag = RESET; // 解码成功标志位 +unsigned char key_data=0; +static unsigned char bit_value = 0; + +/* + NEC红外编码: 引导码 + 地址码 + 地址码(取反) + 数据 + 数据(取反) + 引导吗:0.56ms(低电平) + 2.25ms(高电平) + 数据1: 0.56ms(低电平) + 1.12ms(高电平) +*/ +// 红外解码程序,100us定期执行就可以,将该函数放在100us的定时器中即可。 + + + +void Ir_Decode(void) +{ + static unsigned int l_cnt = 0; // 低电平时间计数 + static unsigned int h_cnt = 0; // 高电平时间计数 + static unsigned int l_cnt_save = 0; // 保存低电平时长 + static unsigned int h_cnt_save = 0; // 保存高电平时长 + static unsigned char falling_edge_valid_flag = RESET; // IR电平由高变低标志位 + static unsigned char rcv_sync_ok_flag = RESET; // 同步码接收成功标志位 + static unsigned char bit_value = 0; // 位解码值 + static unsigned char bit_rcv_cnt = 0; // 位接收个数变量 + + + if( RESET == IR_IN ) + { + if( 0 == l_cnt ) // IR由高变低后立马记录上次测得的高电平时长 + { + h_cnt_save = h_cnt; + falling_edge_valid_flag = SET; + } + + + l_cnt ++; + if( l_cnt > 1600 ) // 防止计数溢出 + { + l_cnt = 1600; + } + h_cnt = 0; // 计数清零 + + } + else + { + if( 0 == h_cnt ) // IR由低变高后立马记录上次测得的低电平时长 + { + l_cnt_save = l_cnt; + } + + h_cnt ++; + if( h_cnt > 1600 ) // 防止计数溢出 + { + h_cnt = 1600; + } + + l_cnt = 0; // 计数清零 + + + if(ir_decode_ok_flag == 1) + { + if(h_cnt > 1200) + ir_decode_ok_flag = 2; // 短按 + } + + } + + + if( SET == falling_edge_valid_flag ) + { + falling_edge_valid_flag = RESET; + + /* 位解码 */ + if( ((l_cnt_save >= 3)&&(l_cnt_save <= 9)) && // 560us低电平, 560us高电平 + ((h_cnt_save >= 3)&&(h_cnt_save <= 9)) ) + { + bit_value = 0; + } + else if( ((l_cnt_save >= 3)&&(l_cnt_save <= 9)) && // 560us低电平,1680us高电平 + ((h_cnt_save >= 14)&&(h_cnt_save <= 20)) ) + { + bit_value = 1; + } + else + { + bit_value = 2; + } + + if( SET == rcv_sync_ok_flag ) + { + if((1 == bit_value) || (0 == bit_value) ) + { + if( bit_rcv_cnt < 8 ) + { + ir_code[0] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 16 ) + { + ir_code[1] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 24 ) + { + ir_code[2] |= (bit_value<< (bit_rcv_cnt%8)); + } + else if( bit_rcv_cnt < 32 ) + { + ir_code[3] |= (bit_value<< (bit_rcv_cnt%8)); + } + + if( bit_rcv_cnt >= 31 ) + { + ir_decode_ok_flag = SET; + rcv_sync_ok_flag = RESET; + } + + bit_rcv_cnt ++; + } + else + { + rcv_sync_ok_flag = RESET; // 位接收错误,重新解码 + } + } + + if( ((l_cnt_save >= 87)&&(l_cnt_save <= 93)) && + ((h_cnt_save >= 42)&&(h_cnt_save <= 48)) ) // 同步码,9ms低电平,4.5ms高电平 + { + rcv_sync_ok_flag = SET; + bit_rcv_cnt = 0; + ir_code[0] = 0; + ir_code[1] = 0; + ir_code[2] = 0; + ir_code[3] = 0; + } + else if(((l_cnt_save >= 87)&&(l_cnt_save <= 93)) && + ((h_cnt_save >= 20)&&(h_cnt_save <= 25)) ) + { + DBG_PRINTF("repeate code\r\n"); + ir_decode_ok_flag = 3; //长按 + } + + } +} + +//获取红外键值 +/* +KEY_OK = 28, +KEY_UP =24, +KEY_DOWN = 82 +KEY_LEFT = 8, +KEY_RIGHT =90, +KEY_1 = 69, +KEY_2 = 70, +KEY_3 = 71, +KEY_4 = 68, +KEY_5 = 64, +KEY_6 = 67, +KEY_7 = 7, +KEY_8 = 21, +KEY_9 =9, +KEY_0 = 25, +KEY_*=22 +KEY_# =13 +*/ + +unsigned char Remote_Scan(void) +{ + unsigned char key_value = 0; + + + // 校验地址码和命令码 + if((ir_code[0] == (unsigned char)~ir_code[1]) && + (ir_code[2] == (unsigned char)~ir_code[3])) + { + key_value = ir_code[2]; // 返回键值 + memset(ir_code, 0, sizeof(ir_code)); + } + + switch(key_value) + { + case 69: + DBG_PRINTF("1\r\n");//显示1 + break; + + case 70: + DBG_PRINTF("2\r\n");//显示2 + break; + + case 71: + DBG_PRINTF("3\r\n");//显示3 + break; + + case 68: + DBG_PRINTF("4\r\n");//显示4 + break; + + case 64: + DBG_PRINTF("5\r\n");//显示5 + break; + + case 67: + DBG_PRINTF("6\r\n");//显示6 + break; + + case 7: + DBG_PRINTF("7\r\n");//显示7 + break; + + case 21: + DBG_PRINTF("8\r\n");//显示8 + break; + + case 9: + DBG_PRINTF("9\r\n");//显示9 + break; + + case 25: + DBG_PRINTF("0\r\n");//显示0 + break; + + case 22: + DBG_PRINTF("*\r\n");//显示ASCII字符 + break; + + case 13: + DBG_PRINTF("#\r\n");//显示ASCII字符 + break; + + case 24: + + DBG_PRINTF("UP\r\n");//显示ASCII字符 + break; + + case 8: + DBG_PRINTF("LEFT\r\n");//显示ASCII字符 + break; + + case 82: + + DBG_PRINTF("DOWN\r\n");//显示ASCII字符 + + break; + + case 90: + DBG_PRINTF("RIGHT\r\n");//显示ASCII字符 + break; + + case 28: + DBG_PRINTF("OK\r\n"); + break; + + default: + + break; + } + + + return key_value; +} + + + + + +void TIMER2_InterruptProcess(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN TIMER2_InterruptProcess */ + Ir_Decode(); + key_data=Remote_Scan(); + + + /* USER CODE END TIMER2_InterruptProcess */ +} + + + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.h b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.h new file mode 100644 index 0000000000000000000000000000000000000000..faa038d5e109f703b2bb5df6fd5cada0acc9c26c --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/ifd.h @@ -0,0 +1,33 @@ +#ifndef __IR_H +#define __IR_H +extern unsigned char ir_code[4]; +extern unsigned char key_data; +void Ir_Decode(void); + +unsigned char Remote_Scan(void); + + + + + + + + + + + + + + + + +#endif + + + + + + + + + diff --git a/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/main.h b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..e26db1d48185ab111905ea35c8411fd4ab3204cb --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/main.h @@ -0,0 +1,67 @@ +/** + * @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. + * @date 2025-04-25 10:40:20 + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_SYSTEM_INIT_H +#define McuMagicTag_SYSTEM_INIT_H + +#include "uart.h" +#include "uart_ex.h" +#include "gpio.h" +#include "timer.h" +#include "timer_ex.h" +#include "crg.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 ir_PIN GPIO_PIN_2 +#define ir_HANDLE g_gpio2 + +extern TIMER_Handle g_timer2; +extern UART_Handle g_uart0; + +extern GPIO_Handle g_gpio2; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void TIMER2_InterruptProcess(void *handle); +void TIMER2_DMAOverFlow_InterruptProcess(void *handle); + +/* 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/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/system_init.c b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..bcc2d3246a0c3c663054cd4ad332b4f7d838f89f --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/generatecode/system_init.c @@ -0,0 +1,156 @@ +/** + * @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. + * @date 2025-04-25 10:40:20 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_RATE 115200 + +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 GPIO_Init(void) +{ + HAL_CRG_IpEnableSet(GPIO2_BASE, IP_CLK_ENABLE); + g_gpio2.baseAddress = GPIO2; + + g_gpio2.pins = GPIO_PIN_2; + 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_NONE); + + return; +} + +__weak void TIMER2_InterruptProcess(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN TIMER2_InterruptProcess */ + /* USER CODE END TIMER2_InterruptProcess */ +} + +static void TIMER2_Init(void) +{ + HAL_CRG_IpEnableSet(TIMER2_BASE, IP_CLK_ENABLE); /* TIMER2 clock enable. */ + unsigned int load = ((float)HAL_CRG_GetIpFreq((void *)TIMER2) / (1u << (TIMERPRESCALER_NO_DIV * 4)) / 1000000u) * 100; + + g_timer2.baseAddress = TIMER2; + g_timer2.load = (load < 1) ? 0 : (load - 1); /* Set timer value immediately */ + g_timer2.bgLoad = (load < 1) ? 0 : (load - 1); /* Set timer value */ + g_timer2.mode = TIMER_MODE_RUN_PERIODIC; /* Run in period mode */ + g_timer2.prescaler = TIMERPRESCALER_NO_DIV; /* Don't frequency division */ + g_timer2.size = TIMER_SIZE_32BIT; /* 1 for 32bit, 0 for 16bit */ + g_timer2.interruptEn = BASE_CFG_ENABLE; + g_timer2.adcSocReqEnable = BASE_CFG_DISABLE; + g_timer2.dmaReqEnable = BASE_CFG_DISABLE; + HAL_TIMER_Init(&g_timer2); + IRQ_Register(IRQ_TIMER2, HAL_TIMER_IrqHandler, &g_timer2); + + HAL_TIMER_RegisterCallback(&g_timer2, TIMER_PERIOD_FIN, TIMER2_InterruptProcess); + IRQ_SetPriority(IRQ_TIMER2, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_TIMER2); +} + +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} + +static void IOConfig(void) +{ + /* Config PIN36 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_0_AS_JTAG_TCK); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_0_AS_JTAG_TCK, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_0_AS_JTAG_TCK, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_0_AS_JTAG_TCK, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_0_AS_JTAG_TCK, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN37 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_1_AS_JTAG_TMS); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_1_AS_JTAG_TMS, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_1_AS_JTAG_TMS, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_1_AS_JTAG_TMS, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_1_AS_JTAG_TMS, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN34 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_2_AS_GPIO2_2); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_2_AS_GPIO2_2, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_2_AS_GPIO2_2, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_2_AS_GPIO2_2, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_2_AS_GPIO2_2, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* 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 */ +} + +void SystemInit(void) +{ + IOConfig(); + UART0_Init(); + TIMER2_Init(); + GPIO_Init(); + + /* USER CODE BEGIN system_init */ + /* USER CODE END system_init */ +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/Infrared_Receiver_sample/user/main.c b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..3467600b3503f1871db9e08f8881d0aa2ab98a93 --- /dev/null +++ b/vendor/yibaina_3061M/Infrared_Receiver_sample/user/main.c @@ -0,0 +1,77 @@ +/** + * @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. + * @date 2025-04-25 10:37:42 + */ + +#include "typedefs.h" +#include "feature.h" +#include "main.h" +#include "debug.h" +#include "ifd.h" +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +TIMER_Handle g_timer2; +UART_Handle g_uart0; +GPIO_Handle g_gpio2; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ +/* USER CODE END 1 */ + + + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + /* USER CODE END 2 */ + SystemInit(); + /* USER CODE BEGIN 3 */ + /* 建议用户放置初始配置代码 */ + HAL_TIMER_Start(&g_timer2); + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + /* 建议用户放置周期性执行代码 */ + // DBG_PRINTF("ir_code[0] :%d\r\n",ir_code[0]); + // DBG_PRINTF("ir_code[1] :%d\r\n",ir_code[1]); + // DBG_PRINTF("ir_code[2] :%d\r\n",ir_code[2]); + // DBG_PRINTF("ir_code[3] :%d\r\n",ir_code[3]); + // DBG_PRINTF("key_data:%d\r\n",key_data); + + + /* USER CODE END 4 */ + } + /* USER CODE BEGIN 5 */ + /* 建议用户放置代码流程 */ + /* USER CODE END 5 */ + return BASE_STATUS_OK; +} + +/* USER CODE BEGIN 6 */ +/* 建议用户放置自定义函数 */ +/* USER CODE END 6 */ + + + + + diff --git a/vendor/yibaina_3061M/demo/sample_gpio_key/readme.md b/vendor/yibaina_3061M/demo/sample_gpio_key/readme.md deleted file mode 100644 index fb6ae9362f7aa6348ad188aae099a3671f0333bc..0000000000000000000000000000000000000000 --- a/vendor/yibaina_3061M/demo/sample_gpio_key/readme.md +++ /dev/null @@ -1,78 +0,0 @@ -# sample_gpio_key - -## 1.1 介绍 - -**功能介绍:** 基于HAL接口完成时钟、GPIO控制器初始化和功能配置。在示例代码中通过中断的方式实现对S2按键的检测。 - -**软件概述:** 使用中断方式实现按键功能。 - -**硬件概述:** 核心板。通过板端丝印可以看出S2按键的GPIO对应GPIO2_4。硬件搭建要求如图所示: - - - -![image-20240829165616356](../../../../docs/pic/tools/image-20240829165616356.png) - -## 1.2 约束与限制 - -### 1.2.1 支持应用运行的芯片和开发板 - - 本示例支持开发板:3061M - -### 1.2.2 支持API版本、SDK版本 - - 本示例支持版本号:SolarA2_1.0.1.2 - -### 1.2.3 支持IDE版本 - - 本示例支持IDE版本号:1.0.0.6; - -## 1.3 效果预览 - - 当用户烧录编译后的示例代码后,初始化和配置完成后,示例代码中在按键没有按下时Debug串口会一直打印等待按键的log信息,当连接的按键按下时功能正常时Debug串口打印成功log信息;功能异常时按下按键时Debug串口还是会一直打印等待按键的log信息。 - -![image-20240829172606786](../../../../docs/pic/sample_gpio_key/image-20240829172606786.png) - -## 1.4 接口介绍 - -#### 1.4.1 HAL_GPIO_Init() - -| **定义:** | void HAL_GPIO_Init(GPIO_Handle *handle); | -| ------------ | ----------------------------------------- | -| **功能:** | 初始化GPIO寄存器值 | -| **参数:** | handle:GPIO_Handle的值 | -| **返回值:** | None | -| **依赖:** | drivers\gpio\common\inc\gpio.h | - -## 1.5 具体实现 - - 步骤一:GPIO管脚选择:示例代码中选择GPIO管脚用于通过中断方式进行按键检测。也可以选择其他GPIO管脚用于按键检测功能测试,在"GPIO_Init()"接口中的"g_gpiox.baseAddress"可以配置其它GPIOX,g_gpiox.pins可以配置“GPIO_PIN_0-GPIO_PIN_7”中的任意一个。 - - 步骤二:GPIO管脚初始化:调用接口"HAL_GPIO_Init()”完成对示例代码中GPIO管脚的方向、电平、中断模式配置。 - -## 1.6 实验流程 - -- 步骤一:在xxx\vendor\yibaina_3061M\demo\sample_gpio_key/文件夹里面内容复制替换到xxx/user/目录下。 - - ![image-20240829174750105](../../../../docs/pic/sample_gpio_key/image-20240829174750105.png) - - -- 步骤二:点击编译按钮![image-20240528173107958](../../../../docs/pic/sample_gpio_key/image-20240528173107958-17249242848691.png),编译成功后终端窗口输出如下图所示。 - ![image-20240624165330284](../../../../docs/pic/tools/image-20240624165330284.png) - - - -- 步骤三:进入工程配置界面。打开要烧录的工程后,单击顶部![image-20240624154427635](../../../../docs/pic/sample_gpio_key/image-20240624154427635-17249243742892.png)的图标,进入工程配置界面->进入程序加载。选择传输方式为“swd”,并配置其他参数。(具体[参考tools目录README搭建环境](https://gitee.com/HiSpark/open_mcu/tree/master/tools)) - - ![image-20240829174913995](../../../../docs/pic/sample_gpio_key/image-20240829174913995.png) - -- 步骤四:单击“烧录”![image-20240624162016190](../../../../docs/pic/tools/image-20240624162016190.png) 按钮,开始烧录。烧录成功后终端窗口输出如下图所示。 - - ![image-20240624162037834](../../../../docs/pic/sample_gpio_key/image-20240624162037834-17249245112874.png) - -* 步骤五 : 当用户烧录编译后的示例代码后,初始化和配置完成后,示例代码中在按键没有按下时Debug串口会一直打印等待按键的log信息,当连接的按键按下时功能正常时Debug串口打印成功log信息;功能异常时按下按键时Debug串口还是会一直打印等待按键的log信息。 - - ![image-20240829172606786](../../../../docs/pic/sample_gpio_key/image-20240829172606786.png) - - - - \ No newline at end of file diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/readme.md b/vendor/yibaina_3061M/mpu6050_oled_sample/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..cb9a4c5ee1559ba5cb098bb957d5f63b730de448 --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/readme.md @@ -0,0 +1,30 @@ +# mpu6050_oled_sample + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板的MPU6050六轴姿态传感器案例 + +**【环境要求】** + +- OLED、MPU6050使用IIC通信,该案例接同一个IIC引脚,一主多从 + +- 接线方式: + + ic0_SCL---GPIO4_5---J2_21 + + ic0_SDA---GPIO4_3---J2_26 + + 3.3v ---J1_15 + + GND---J1_7 + + + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + +【操作说明】 + +- 调用oled.h里的显示接口即可 +- 挪动MPU6050,oled会显示pitch 角和 roll 角 diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/feature.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..aaceedee5df301e51c7c897f9d796e39341d6578 --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/feature.h @@ -0,0 +1,120 @@ +/** + * @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. + * @date 2025-04-25 17:06:08 + */ + +#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. */ + +#define MCS_PARAM_CHECK MACRO_ENABLE +#define APT_PARAM_CHECK MACRO_ENABLE +#define ADC_PARAM_CHECK MACRO_ENABLE +#define CAPM_PARAM_CHECK MACRO_ENABLE +#define CRG_PARAM_CHECK MACRO_ENABLE +#define I2C_PARAM_CHECK MACRO_ENABLE +#define UART_PARAM_CHECK MACRO_ENABLE +#define SPI_PARAM_CHECK MACRO_ENABLE +#define TIMER_PARAM_CHECK MACRO_ENABLE +#define IWDG_PARAM_CHECK MACRO_ENABLE +#define WWDG_PARAM_CHECK MACRO_ENABLE +#define GPIO_PARAM_CHECK MACRO_ENABLE +#define GPT_PARAM_CHECK MACRO_ENABLE +#define DMA_PARAM_CHECK MACRO_ENABLE +#define CRC_PARAM_CHECK MACRO_ENABLE +#define CFD_PARAM_CHECK MACRO_ENABLE +#define CMM_PARAM_CHECK MACRO_ENABLE +#define CAN_PARAM_CHECK MACRO_ENABLE +#define FLASH_PARAM_CHECK MACRO_ENABLE +#define PMC_PARAM_CHECK MACRO_ENABLE +#define ACMP_PARAM_CHECK MACRO_ENABLE +#define DAC_PARAM_CHECK MACRO_ENABLE +#define PGA_PARAM_CHECK MACRO_ENABLE +#define IOCMG_PARAM_CHECK MACRO_ENABLE +#define QDM_PARAM_CHECK MACRO_ENABLE + +/* 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/yibaina_3061M/demo/sample_gpio_key/generatecode/main.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/main.h similarity index 94% rename from vendor/yibaina_3061M/demo/sample_gpio_key/generatecode/main.h rename to vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/main.h index c77e0f2ece54dd83d99b719c2dccffc08d908aeb..2ffce61d28f5f7624763ee9c363355b28bdab860 100644 --- a/vendor/yibaina_3061M/demo/sample_gpio_key/generatecode/main.h +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/main.h @@ -18,6 +18,7 @@ * @file main.h * @author MCU Driver Team * @brief This file contains driver init functions. + * @date 2025-04-25 17:06:08 */ /* Define to prevent recursive inclusion ------------------------------------- */ @@ -26,9 +27,12 @@ #include "uart.h" #include "uart_ex.h" -#include "gpio.h" +#include "i2c.h" +#include "i2c_ex.h" #include "crg.h" #include "iocmg.h" +#include "dma.h" +#include "dma_ex.h" #define IO_SPEED_FAST 0x00U #define IO_SPEED_SLOW 0x01U @@ -44,14 +48,11 @@ #define XTAL_DRV_LEVEL1 0x00U extern UART_Handle g_uart0; - -extern GPIO_Handle g_gpio2; - +extern I2C_Handle g_i2c0; +extern DMA_Handle g_dmac; BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); void SystemInit(void); -void GPIO_CallBackFunc(void *param); - /* USER CODE BEGIN 0 */ /* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ /* USER CODE END 0 */ diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/system_init.c b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..746fc99e6e1f71773971c289fa8dbd3b2e599fbe --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/generatecode/system_init.c @@ -0,0 +1,215 @@ +/** + * @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. + * @date 2025-04-25 17:06:08 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + + +#define UART0_BAUD_RATE 115200 + +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; +} + + +__weak void I2C0TxCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0TxCallback */ + /* USER CODE END I2C0TxCallback */ +} + +__weak void I2C0RxCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0RxCallback */ + /* USER CODE END I2C0RxCallback */ +} + +__weak void I2C0ErrorCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN I2C0ErrorCallback */ + /* USER CODE END I2C0ErrorCallback */ +} + +static void I2C0_Init(void) +{ + HAL_CRG_IpEnableSet(I2C0_BASE, IP_CLK_ENABLE); /* I2C0 clock enable. */ + g_i2c0.baseAddress = I2C0; + + g_i2c0.functionMode = I2C_MODE_SELECT_MASTER_ONLY; + g_i2c0.addrMode = I2C_7_BITS; + g_i2c0.sdaHoldTime = 10; /* 10 is sda Hold Time */ + g_i2c0.freq = 400000; /* freqence is 400000 */ + g_i2c0.transferBuff = NULL; + g_i2c0.ignoreAckFlag = BASE_CFG_DISABLE; + g_i2c0.handleEx.spikeFilterTime = 0; + g_i2c0.handleEx.sdaDelayTime = 0; + g_i2c0.timeout = 10000; /* 10000 is time out */ + g_i2c0.state = I2C_STATE_RESET; + g_i2c0.rxWaterMark = 1; /* 1 is Rx Threshold configuration */ + g_i2c0.txWaterMark = 12; /* 12 is Tx Threshold configuration */ + g_i2c0.dmaHandle = &g_dmac; + g_i2c0.txDmaCh = DMA_CHANNEL_ONE; + g_i2c0.rxDmaCh = DMA_CHANNEL_ZERO; + HAL_I2C_Init(&g_i2c0); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_MASTER_TX_COMPLETE_CB_ID, I2C0TxCallback); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_MASTER_RX_COMPLETE_CB_ID, I2C0RxCallback); + HAL_I2C_RegisterCallback(&g_i2c0, I2C_ERROR_CB_ID, I2C0ErrorCallback); +} +static void DMA_Channel0Init(void *handle) +{ + DMA_ChannelParam dma_param; + dma_param.direction = DMA_PERIPH_TO_MEMORY_BY_DMAC; + dma_param.srcAddrInc = DMA_ADDR_UNALTERED; + dma_param.destAddrInc = DMA_ADDR_INCREASE; + dma_param.srcPeriph = DMA_REQUEST_I2C0_RX; + dma_param.destPeriph = DMA_REQUEST_MEM; + 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_Channel1Init(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_I2C0_TX; + dma_param.srcWidth = DMA_TRANSWIDTH_WORD; + dma_param.destWidth = DMA_TRANSWIDTH_WORD; + 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_ONE); +} + +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_i2c0)); + HAL_DMA_SetChannelPriorityEx(&g_dmac, DMA_CHANNEL_ZERO, DMA_PRIORITY_HIGHEST); + DMA_Channel1Init((void *)(&g_i2c0)); + HAL_DMA_SetChannelPriorityEx(&g_dmac, DMA_CHANNEL_ONE, DMA_PRIORITY_HIGHEST); +} +static void UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} + + + +static void IOConfig(void) +{ + /* Config PIN36 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_0_AS_JTAG_TCK); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_0_AS_JTAG_TCK, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_0_AS_JTAG_TCK, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_0_AS_JTAG_TCK, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_0_AS_JTAG_TCK, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN37 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_1_AS_JTAG_TMS); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_1_AS_JTAG_TMS, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_1_AS_JTAG_TMS, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_1_AS_JTAG_TMS, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_1_AS_JTAG_TMS, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* 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 PIN15 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_5_AS_I2C0_SCL); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_5_AS_I2C0_SCL, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_5_AS_I2C0_SCL, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_5_AS_I2C0_SCL, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_5_AS_I2C0_SCL, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN16 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_3_AS_I2C0_SDA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_3_AS_I2C0_SDA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_3_AS_I2C0_SDA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_3_AS_I2C0_SDA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_3_AS_I2C0_SDA, DRIVER_RATE_2); /* Output signal edge fast/slow */ +} + +void SystemInit(void) +{ + IOConfig(); + UART0_Init(); + DMA_Init(); + I2C0_Init(); + + /* USER CODE BEGIN system_init */ + /* USER CODE END system_init */ +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/main.c b/vendor/yibaina_3061M/mpu6050_oled_sample/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..f1804773fa7e47597ba6bb57d014c925c63a7c6b --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/main.c @@ -0,0 +1,92 @@ +/** + * @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. + * @date 2025-04-25 17:06:08 + */ + +#include "typedefs.h" +#include "feature.h" +#include "main.h" +#include "oled.h" +#include "debug.h" +#include "mpu6050.h" +#include "kalman.h" + +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +UART_Handle g_uart0; +I2C_Handle g_i2c0; +DMA_Handle g_dmac; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ +/* USER CODE END 1 */ + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + /* USER CODE END 2 */ + SystemInit(); + /* USER CODE BEGIN 3 */ + + // oled初始化 + OLED_Init(); + // OLED_ShowString(5, 3, "hello Hispark!", 16); + + // mpu6050初始化 + mpu6050_init(); + Kalman_Init(); + + OLED_displaystr(16,2,"Pitch:"); + OLED_displaystr(16,6,"Roll:"); + + + + // OLED_displaystr(0,0,"档位:1"); + // OLED_displaystr(0,3,"电机速度:12RPM"); + + + /* 建议用户放置初始配置代码 */ + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + /* 建议用户放置周期性执行代码 */ + // 原始数据获取 + + // BASE_FUNC_DelayMs(10); + Kalman_Calculate(); + OLED_ShowNum(64,2,pitch,3,16); + OLED_ShowNum(64,6,roll,3,16); + DBG_PRINTF("yaw=%f,roll= %f,pitch=%f\r\n", yaw,roll, pitch); + + + /* 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 diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.c b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.c new file mode 100644 index 0000000000000000000000000000000000000000..ea45c401900c7a448cdcb07351d97e79ca194fdb --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.c @@ -0,0 +1,102 @@ +#include "mpu6050.h" +#include "kalman.h" +#include "math.h" + +/*定义卡尔曼滤波所需要的基本变量*/ +KalmanFilter kf_pitch; // 翻滚角 +KalmanFilter kf_roll; // 俯仰角 +KalmanFilter kf_yaw; // 偏航角 +__INT16_TYPE__ AccX, AccY, AccZ, GYROX, GYROY, GYROZ; +float gyroXrate, gyroYrate,gyroZrate,accPitch, accRoll; +float pitch, roll,yaw; + + + + +// 卡尔曼滤波初始化 +void KalmanFilter_Init(KalmanFilter *kf) { + // 重置协方差矩阵 + kf->P[0][0] = 0.0f; + kf->P[0][1] = 0.0f; + kf->P[1][0] = 0.0f; + kf->P[1][1] = 0.0f; + + // 设置默认噪声参数 + kf->Q_angle = 0.001f; + kf->Q_bias = 0.003f; + kf->R_measure = 0.03f; + + kf->angle = 0.0f; + kf->bias = 0.0f; + kf->rate = 0.0f; +} + +// 卡尔曼滤波更新 +float KalmanFilter_Update(KalmanFilter *kf, float newAngle, float newRate, float dt) { + // 预测阶段 + kf->rate = newRate - kf->bias; + kf->angle += dt * kf->rate; + + // 更新误差协方差矩阵 + kf->P[0][0] += dt * (dt*kf->P[1][1] - kf->P[0][1] - kf->P[1][0] + kf->Q_angle); + kf->P[0][1] -= dt * kf->P[1][1]; + kf->P[1][0] -= dt * kf->P[1][1]; + kf->P[1][1] += kf->Q_bias * dt; + + // 计算卡尔曼增益 + float S = kf->P[0][0] + kf->R_measure; + float K[2] = {kf->P[0][0]/S, kf->P[1][0]/S}; + + // 更新估计值 + float y = newAngle - kf->angle; + kf->angle += K[0] * y; + kf->bias += K[1] * y; + + // 更新协方差矩阵 + float P00_temp = kf->P[0][0]; + float P01_temp = kf->P[0][1]; + + kf->P[0][0] -= K[0] * P00_temp; + kf->P[0][1] -= K[0] * P01_temp; + kf->P[1][0] -= K[1] * P00_temp; + kf->P[1][1] -= K[1] * P01_temp; + + return kf->angle; +} + +// 三轴卡尔曼滤波初始化 +void Kalman_Init() { + KalmanFilter_Init(&kf_pitch); + KalmanFilter_Init(&kf_roll); + KalmanFilter_Init(&kf_yaw); +} + +// 三轴姿态计算 +void Kalman_Calculate() { + // 获取原始数据 + MPU6050_GetData(&AccX, &AccY, &AccZ, &GYROX, &GYROY, &GYROZ); + + // 转换陀螺仪数据为度/秒 + gyroXrate = GYROX / 131.0f; + gyroYrate = GYROY / 131.0f; + gyroZrate = GYROZ / 131.0f; + + // 计算加速度计角度(俯仰和横滚) + accPitch = atan2f(AccY, AccZ) * 180.0f / 3.141593f; + accRoll = atan2f(AccX, AccZ) * 180.0f / 3.141593f; + + // 注意:加速度计无法直接测量偏航角,需要磁力计或使用陀螺仪积分 + + // 卡尔曼滤波更新(采样时间10ms) + pitch = KalmanFilter_Update(&kf_pitch, accPitch, gyroYrate, 0.01f); + roll = KalmanFilter_Update(&kf_roll, accRoll, gyroXrate, 0.01f); + + // 偏航角计算(仅使用陀螺仪积分,会随时间漂移) + // 实际应用中应结合磁力计数据 + yaw = KalmanFilter_Update(&kf_yaw, yaw, gyroZrate, 0.01f); + + // 可选:限制角度范围到0-360度 + if(yaw < 0) yaw += 360.0f; + if(yaw >= 360.0f) yaw -= 360.0f; +} + diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.h new file mode 100644 index 0000000000000000000000000000000000000000..a1f318c5155ab0201137424e812c54a98ca9566d --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/kalman.h @@ -0,0 +1,31 @@ +#ifndef __KALMAN_H__ +#define __KALMAN_H__ + + + +void Kalman_Init(void); +void Kalman_Calculate(void); +extern float pitch, roll,yaw; + +typedef struct +{ + float Q_angle; + float Q_bias; + float R_measure; + float angle; + float bias; + float rate; + + float P[2][2]; +} KalmanFilter; + +extern __INT16_TYPE__ AccX, AccY, AccZ, GYROX, GYROY, GYROZ; +extern float gyroXrate, gyroYrate,gyroZrate, accPitch, accRoll; + +void Kalman_Init(void); +void Kalman_Calculate(void); +void KalmanFilter_Init(KalmanFilter *kf); +float KalmanFilter_Update(KalmanFilter *kf, float newAngle, float newRate, float dt); +void MPU6050_GatResult(float *yaw ,float *roll ,float *pitch); + +#endif diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.c b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.c new file mode 100644 index 0000000000000000000000000000000000000000..78cc343ce6f7e3d70f331c507eb86f7530e482a7 --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.c @@ -0,0 +1,117 @@ +#include "MPU6050.h" +#include "debug.h" +#include "main.h" + +#define I2C_SAMPLE_OLED_ADDR_SIZE 1 +#define I2C_SAMPLE_MAX_TIMEOUT 10000 +#define I2C_SAMPLE_OLED_PAGE_SIZE 8 //一次写一个字节 + +#define IIC_WRITE 0xd0 +#define IIC_READ IIC_WRITE+1 + +// 传入传感器的寄存器地址 +__UINT8_TYPE__ IIC_my_ReadData(__UINT8_TYPE__ addr) +{ + __UINT8_TYPE__ databuff[10] = {0}; + BASE_StatusType ret = BASE_STATUS_OK; + unsigned char tempAddr[I2C_SAMPLE_OLED_ADDR_SIZE]; + + tempAddr[0] = addr; + ret = HAL_I2C_MasterWriteBlocking(&g_i2c0, IIC_WRITE, tempAddr, + I2C_SAMPLE_OLED_ADDR_SIZE, I2C_SAMPLE_MAX_TIMEOUT); + if (ret != BASE_STATUS_OK) + { + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + /* Read data from eeprom. */ + ret = HAL_I2C_MasterReadBlocking(&g_i2c0, IIC_READ, databuff, + 1, I2C_SAMPLE_MAX_TIMEOUT); + if (ret != BASE_STATUS_OK) + { + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + return databuff[0]; +} + +// 传感器内部的寄存器地址,写入寄存器的值,写入的长度 +BASE_StatusType IIC_my_WriteData(unsigned int addr, unsigned char dat, unsigned int len) +{ + unsigned char tempWrite[I2C_SAMPLE_OLED_PAGE_SIZE / 8 + I2C_SAMPLE_OLED_ADDR_SIZE]; + // 写寄存器地址和存储发送数据 通常1+1 2个字节 + BASE_StatusType ret = BASE_STATUS_OK; + /* Set the memory address of eeprom. */ + tempWrite[0] = addr; + tempWrite[1] = dat; + ret = HAL_I2C_MasterWriteBlocking(&g_i2c0, IIC_WRITE, tempWrite, + len + I2C_SAMPLE_OLED_ADDR_SIZE, I2C_SAMPLE_MAX_TIMEOUT); + // len + I2C_SAMPLE_OLED_ADDR_SIZE ,写的长度加上写的寄存器地址长度,通常1+1 2个字节 + if (ret != BASE_STATUS_OK) + { + DBG_PRINTF("LINE:%d,Write Data Fail!,ret:%d\r\n", __LINE__, ret); + } + return ret; +} + +__UINT8_TYPE__ MPU6050_GetID(void) +{ + return IIC_my_ReadData(MPU6050_WHO_AM_I); // 返回WHO_AM_I寄存器的值 +} + +void mpu6050_init(void) +{ + IIC_my_WriteData(MPU6050_PWR_MGMT_1, 0x80, 1); + + BASE_FUNC_DELAY_MS(100); // 延迟 100ms 让 MPU6050 启动 + IIC_my_WriteData(MPU6050_PWR_MGMT_1, 0x00, 1); // 设置电源管理寄存器为 0x00,使能 MPU6050 + IIC_my_WriteData(MPU6050_CONFIG, 0x06, 1); // 低通滤波频率,典型值:0x06(5Hz) + + IIC_my_WriteData(MPU6050_SMPLRT_DIV, 0x07, 1); // 陀螺仪采样率,典型值:0x07(125Hz) + + IIC_my_WriteData(MPU6050_RA_INT_ENABLE, 0X00, 1); // 关闭所有中断 + IIC_my_WriteData(MPU6050_RA_USER_CTRL, 0X00, 1); // I2C主模式关闭 + IIC_my_WriteData(MPU6050_RA_FIFO_EN, 0X00, 1); // 关闭FIFO + IIC_my_WriteData(MPU6050_RA_INT_PIN_CFG, 0X80, 1); // 中断的逻辑电平模式,设置为0,中断信号为高电;设置为1,中断信号为低电平时。 + // MotionInterrupt(); // 运动中断 + IIC_my_WriteData(MPU6050_RA_CONFIG, 0x04, 1); // 配置外部引脚采样和DLPF数字低通滤波器 + IIC_my_WriteData(MPU6050_RA_ACCEL_CONFIG, 0x1C, 1); // 加速度传感器量程和高通滤波器配置 + IIC_my_WriteData(MPU6050_RA_INT_PIN_CFG, 0X1C, 1); // INT引脚低电平平时 + IIC_my_WriteData(MPU6050_RA_INT_ENABLE, 0x40, 1); // 中断使能寄存器 + + IIC_my_WriteData(MPU6050_GYRO_CONFIG, 0x18, 1); // 陀螺仪自检及测量范围,典型值:0x18(不自检,2000deg/s) + IIC_my_WriteData(MPU6050_ACCEL_CONFIG, 0x01, 1); // 加速计自检、测量范围及高通滤波频率,典型值:0x01(不自检,2G,5Hz) + + +} + +// 将两字节数据读取并合成一个16位数据 +void MPU6050_GetData(__INT16_TYPE__ *AccX, __INT16_TYPE__ *AccY, __INT16_TYPE__ *AccZ, + __INT16_TYPE__ *GYROX, __INT16_TYPE__ *GYROY, __INT16_TYPE__ *GYROZ) +{ + __UINT8_TYPE__ DataH, DataL; // 定义数据高8位和低8位的变量 + + DataH = IIC_my_ReadData(MPU6050_ACCEL_XOUT_H); // 读取加速度计X轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_ACCEL_XOUT_L); // 读取加速度计X轴的低8位数据 + *AccX = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 + + DataH = IIC_my_ReadData(MPU6050_ACCEL_YOUT_H); // 读取加速度计Y轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_ACCEL_YOUT_L); // 读取加速度计Y轴的低8位数据 + *AccY = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 + + DataH = IIC_my_ReadData(MPU6050_ACCEL_ZOUT_H); // 读取加速度计Z轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_ACCEL_ZOUT_L); // 读取加速度计Z轴的低8位数据 + *AccZ = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 + + DataH = IIC_my_ReadData(MPU6050_GYRO_XOUT_H); // 读取陀螺仪X轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_GYRO_XOUT_L); // 读取陀螺仪X轴的低8位数据 + *GYROX = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 + + DataH = IIC_my_ReadData(MPU6050_GYRO_YOUT_H); // 读取陀螺仪Y轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_GYRO_YOUT_L); // 读取陀螺仪Y轴的低8位数据 + *GYROY = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 + + DataH = IIC_my_ReadData(MPU6050_GYRO_ZOUT_H); // 读取陀螺仪Z轴的高8位数据 + DataL = IIC_my_ReadData(MPU6050_GYRO_ZOUT_L); // 读取陀螺仪Z轴的低8位数据 + *GYROZ = (DataH << 8) | DataL; // 数据拼接,通过输出参数返回 +} diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.h new file mode 100644 index 0000000000000000000000000000000000000000..e40260f197c311103b734fb3c128233f3d641398 --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/mpu6050/mpu6050.h @@ -0,0 +1,52 @@ +#ifndef __MPU6050_H__ +#define __MPU6050_H__ + +#include "main.h" + +#define MPU6050_SMPLRT_DIV 0x19 +#define MPU6050_CONFIG 0x1A +#define MPU6050_GYRO_CONFIG 0x1B +#define MPU6050_ACCEL_CONFIG 0x1C + +#define MPU6050_ACCEL_XOUT_H 0x3B +#define MPU6050_ACCEL_XOUT_L 0x3C +#define MPU6050_ACCEL_YOUT_H 0x3D +#define MPU6050_ACCEL_YOUT_L 0x3E +#define MPU6050_ACCEL_ZOUT_H 0x3F +#define MPU6050_ACCEL_ZOUT_L 0x40 +#define MPU6050_TEMP_OUT_H 0x41 +#define MPU6050_TEMP_OUT_L 0x42 +#define MPU6050_GYRO_XOUT_H 0x43 +#define MPU6050_GYRO_XOUT_L 0x44 +#define MPU6050_GYRO_YOUT_H 0x45 +#define MPU6050_GYRO_YOUT_L 0x46 +#define MPU6050_GYRO_ZOUT_H 0x47 +#define MPU6050_GYRO_ZOUT_L 0x48 + +#define MPU6050_PWR_MGMT_1 0x6B +#define MPU6050_PWR_MGMT_2 0x6C +#define MPU6050_WHO_AM_I 0x75 +// *********************************************** +#define MPU6050_ADDRESS_AD0_LOW 0x68 // address pin low (GND), default for InvenSense evaluation board +#define MPU6050_RA_CONFIG 0x1A +#define MPU6050_RA_ACCEL_CONFIG 0x1C +#define MPU6050_RA_FF_THR 0x1D +#define MPU6050_RA_FF_DUR 0x1E +#define MPU6050_RA_MOT_THR 0x1F // 运动检测阀值设置寄存器 +#define MPU6050_RA_MOT_DUR 0x20 // 运动检测时间阀值 +#define MPU6050_RA_ZRMOT_THR 0x21 +#define MPU6050_RA_ZRMOT_DUR 0x22 +#define MPU6050_RA_FIFO_EN 0x23 +#define MPU6050_RA_INT_PIN_CFG 0x37 // 中断/旁路设置寄存器 +#define MPU6050_RA_INT_ENABLE 0x38 // 中断使能寄存器 +#define MPU6050_RA_TEMP_OUT_H 0x41 +#define MPU6050_RA_USER_CTRL 0x6A +#define MPU6050_RA_PWR_MGMT_1 0x6B +#define MPU6050_RA_WHO_AM_I 0x75 + +void mpu6050_init(void); +__UINT8_TYPE__ MPU6050_GetID(void); +__UINT8_TYPE__ IIC_my_ReadData(__UINT8_TYPE__ addr); +BASE_StatusType IIC_my_WriteData(unsigned int addr, unsigned char dat, unsigned int len); +void MPU6050_GetData(__INT16_TYPE__ *AccX, __INT16_TYPE__ *AccY, __INT16_TYPE__ *AccZ, __INT16_TYPE__ *GYROX,__INT16_TYPE__ *GyroY,__INT16_TYPE__ *GyroZ); +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled.h new file mode 100644 index 0000000000000000000000000000000000000000..2471bacdcc33f7d705f5ccf9c1280bd4834bb3df --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled.h @@ -0,0 +1,46 @@ +#ifndef __OLED__H__ +#define __OLED__H__ + +#define OLED_CMD 0 //写命令 +#define OLED_DATA 1 //写数据 + +#define OLED_MODE 0 +#define SIZE 8 +#define XLevelL 0x00 +#define XLevelH 0x10 +#define Max_Column 128 +#define Max_Row 64 +#define Brightness 0xFF +#define X_WIDTH 128 +#define Y_WIDTH 64 + +BASE_StatusType I2C_Read(unsigned char addr, unsigned char *buffer, unsigned int length); +BASE_StatusType I2C_Write(unsigned char addr, unsigned char data, unsigned int length); + +void OLED_Init(void); + +void OLED_WriteCommand(unsigned char IIC_Command); +void OLED_WriteData(unsigned char IIC_Data); + +void OLED_Write_DataOrCommand(unsigned dat,unsigned cmd); +void OLED_Clear(void); + +void OLED_Display_On(void); + +void OLED_Set_Pos(unsigned char x, unsigned char y); + +void OLED_ShowChar(unsigned char x,unsigned char y,unsigned char chr,unsigned char Char_Size); +void OLED_ShowNum(unsigned char x,unsigned char y,int num,unsigned char len,unsigned char size); +void OLED_ShowString(unsigned char x,unsigned char y,char *chr,unsigned char Char_Size); + +//显示汉字 +void OLED_displaychina(unsigned char x,unsigned char y,unsigned char *ch); + +void OLED_displaystr(unsigned char col,unsigned char page,unsigned char *str); + +unsigned int oled_pow(unsigned char m,unsigned char n); + + +void OLED_displaychar(unsigned char col,unsigned char page,unsigned char eng); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled_fonts.h b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled_fonts.h new file mode 100644 index 0000000000000000000000000000000000000000..2329281a40b36f93a4d9df2aa075ee8925418495 --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/inc/oled_fonts.h @@ -0,0 +1,562 @@ + + + + +//常用ASCII表 +//偏移量32 +//ASCII字符集 +//偏移量32 + +/************************************6*8的点阵************************************/ +const unsigned char F6x8[][6] = { +{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},// sp +{0x00, 0x00, 0x00, 0x2f, 0x00, 0x00},// ! +{0x00, 0x00, 0x07, 0x00, 0x07, 0x00},// " +{0x00, 0x14, 0x7f, 0x14, 0x7f, 0x14},// # +{0x00, 0x24, 0x2a, 0x7f, 0x2a, 0x12},// $ +{0x00, 0x62, 0x64, 0x08, 0x13, 0x23},// % +{0x00, 0x36, 0x49, 0x55, 0x22, 0x50},// & +{0x00, 0x00, 0x05, 0x03, 0x00, 0x00},// ' +{0x00, 0x00, 0x1c, 0x22, 0x41, 0x00},// ( +{0x00, 0x00, 0x41, 0x22, 0x1c, 0x00},// ) +{0x00, 0x14, 0x08, 0x3E, 0x08, 0x14},// * +{0x00, 0x08, 0x08, 0x3E, 0x08, 0x08},// + +{0x00, 0x00, 0x00, 0xA0, 0x60, 0x00},// , +{0x00, 0x08, 0x08, 0x08, 0x08, 0x08},// - +{0x00, 0x00, 0x60, 0x60, 0x00, 0x00},// . +{0x00, 0x20, 0x10, 0x08, 0x04, 0x02},// / +{0x00, 0x3E, 0x51, 0x49, 0x45, 0x3E},// 0 +{0x00, 0x00, 0x42, 0x7F, 0x40, 0x00},// 1 +{0x00, 0x42, 0x61, 0x51, 0x49, 0x46},// 2 +{0x00, 0x21, 0x41, 0x45, 0x4B, 0x31},// 3 +{0x00, 0x18, 0x14, 0x12, 0x7F, 0x10},// 4 +{0x00, 0x27, 0x45, 0x45, 0x45, 0x39},// 5 +{0x00, 0x3C, 0x4A, 0x49, 0x49, 0x30},// 6 +{0x00, 0x01, 0x71, 0x09, 0x05, 0x03},// 7 +{0x00, 0x36, 0x49, 0x49, 0x49, 0x36},// 8 +{0x00, 0x06, 0x49, 0x49, 0x29, 0x1E},// 9 +{0x00, 0x00, 0x36, 0x36, 0x00, 0x00},// : +{0x00, 0x00, 0x56, 0x36, 0x00, 0x00},// ; +{0x00, 0x08, 0x14, 0x22, 0x41, 0x00},// < +{0x00, 0x14, 0x14, 0x14, 0x14, 0x14},// = +{0x00, 0x00, 0x41, 0x22, 0x14, 0x08},// > +{0x00, 0x02, 0x01, 0x51, 0x09, 0x06},// ? +{0x00, 0x32, 0x49, 0x59, 0x51, 0x3E},// @ +{0x00, 0x7C, 0x12, 0x11, 0x12, 0x7C},// A +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x36},// B +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x22},// C +{0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C},// D +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x41},// E +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x01},// F +{0x00, 0x3E, 0x41, 0x49, 0x49, 0x7A},// G +{0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F},// H +{0x00, 0x00, 0x41, 0x7F, 0x41, 0x00},// I +{0x00, 0x20, 0x40, 0x41, 0x3F, 0x01},// J +{0x00, 0x7F, 0x08, 0x14, 0x22, 0x41},// K +{0x00, 0x7F, 0x40, 0x40, 0x40, 0x40},// L +{0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F},// M +{0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F},// N +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E},// O +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x06},// P +{0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E},// Q +{0x00, 0x7F, 0x09, 0x19, 0x29, 0x46},// R +{0x00, 0x46, 0x49, 0x49, 0x49, 0x31},// S +{0x00, 0x01, 0x01, 0x7F, 0x01, 0x01},// T +{0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F},// U +{0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F},// V +{0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F},// W +{0x00, 0x63, 0x14, 0x08, 0x14, 0x63},// X +{0x00, 0x07, 0x08, 0x70, 0x08, 0x07},// Y +{0x00, 0x61, 0x51, 0x49, 0x45, 0x43},// Z +{0x00, 0x00, 0x7F, 0x41, 0x41, 0x00},// [ +{0x00, 0x55, 0x2A, 0x55, 0x2A, 0x55},// 55 +{0x00, 0x00, 0x41, 0x41, 0x7F, 0x00},// ] +{0x00, 0x04, 0x02, 0x01, 0x02, 0x04},// ^ +{0x00, 0x40, 0x40, 0x40, 0x40, 0x40},// _ +{0x00, 0x00, 0x01, 0x02, 0x04, 0x00},// ' +{0x00, 0x20, 0x54, 0x54, 0x54, 0x78},// a +{0x00, 0x7F, 0x48, 0x44, 0x44, 0x38},// b +{0x00, 0x38, 0x44, 0x44, 0x44, 0x20},// c +{0x00, 0x38, 0x44, 0x44, 0x48, 0x7F},// d +{0x00, 0x38, 0x54, 0x54, 0x54, 0x18},// e +{0x00, 0x08, 0x7E, 0x09, 0x01, 0x02},// f +{0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C},// g +{0x00, 0x7F, 0x08, 0x04, 0x04, 0x78},// h +{0x00, 0x00, 0x44, 0x7D, 0x40, 0x00},// i +{0x00, 0x40, 0x80, 0x84, 0x7D, 0x00},// j +{0x00, 0x7F, 0x10, 0x28, 0x44, 0x00},// k +{0x00, 0x00, 0x41, 0x7F, 0x40, 0x00},// l +{0x00, 0x7C, 0x04, 0x18, 0x04, 0x78},// m +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x78},// n +{0x00, 0x38, 0x44, 0x44, 0x44, 0x38},// o +{0x00, 0xFC, 0x24, 0x24, 0x24, 0x18},// p +{0x00, 0x18, 0x24, 0x24, 0x18, 0xFC},// q +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x08},// r +{0x00, 0x48, 0x54, 0x54, 0x54, 0x20},// s +{0x00, 0x04, 0x3F, 0x44, 0x40, 0x20},// t +{0x00, 0x3C, 0x40, 0x40, 0x20, 0x7C},// u +{0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C},// v +{0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C},// w +{0x00, 0x44, 0x28, 0x10, 0x28, 0x44},// x +{0x00, 0x1C, 0xA0, 0xA0, 0xA0, 0x7C},// y +{0x00, 0x44, 0x64, 0x54, 0x4C, 0x44},// z +{0x14, 0x14, 0x14, 0x14, 0x14, 0x14},// horiz lines +}; + +/****************************************8*16的点阵************************************/ +const unsigned char F8X16[]={ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,// 0 + 0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x00,//! 1 + 0x00,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//" 2 + 0x40,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x00,//# 3 + 0x00,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x00,//$ 4 + 0xF0,0x08,0xF0,0x00,0xE0,0x18,0x00,0x00,0x00,0x21,0x1C,0x03,0x1E,0x21,0x1E,0x00,//% 5 + 0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x24,0x19,0x27,0x21,0x10,//& 6 + 0x10,0x16,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//' 7 + 0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,//( 8 + 0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,//) 9 + 0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,//* 10 + 0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x1F,0x01,0x01,0x01,0x00,//+ 11 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xB0,0x70,0x00,0x00,0x00,0x00,0x00,//, 12 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,//- 13 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,//. 14 + 0x00,0x00,0x00,0x00,0x80,0x60,0x18,0x04,0x00,0x60,0x18,0x06,0x01,0x00,0x00,0x00,/// 15 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,//0 16 + 0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//1 17 + 0x00,0x70,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,//2 18 + 0x00,0x30,0x08,0x88,0x88,0x48,0x30,0x00,0x00,0x18,0x20,0x20,0x20,0x11,0x0E,0x00,//3 19 + 0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00,//4 20 + 0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00,//5 21 + 0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00,//6 22 + 0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00,//7 23 + 0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,//8 24 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x00,0x31,0x22,0x22,0x11,0x0F,0x00,//9 25 + 0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,//: 26 + 0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x00,0x00,0x00,0x00,//; 27 + 0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,//< 28 + 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x00,//= 29 + 0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,//> 30 + 0x00,0x70,0x48,0x08,0x08,0x08,0xF0,0x00,0x00,0x00,0x00,0x30,0x36,0x01,0x00,0x00,//? 31 + 0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x24,0x23,0x14,0x0B,0x00,//@ 32 + 0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,//A 33 + 0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,//B 34 + 0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,//C 35 + 0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,//D 36 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,//E 37 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,//F 38 + 0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,//G 39 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,//H 40 + 0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//I 41 + 0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,//J 42 + 0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,//K 43 + 0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,//L 44 + 0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x00,0x3F,0x00,0x3F,0x20,0x00,//M 45 + 0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,//N 46 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,//O 47 + 0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,//P 48 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x18,0x24,0x24,0x38,0x50,0x4F,0x00,//Q 49 + 0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,//R 50 + 0x00,0x70,0x88,0x08,0x08,0x08,0x38,0x00,0x00,0x38,0x20,0x21,0x21,0x22,0x1C,0x00,//S 51 + 0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//T 52 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//U 53 + 0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,//V 54 + 0xF8,0x08,0x00,0xF8,0x00,0x08,0xF8,0x00,0x03,0x3C,0x07,0x00,0x07,0x3C,0x03,0x00,//W 55 + 0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,//X 56 + 0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//Y 57 + 0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,//Z 58 + 0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,//[ 59 + 0x00,0x0C,0x30,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,//\ 60 + 0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,//] 61 + 0x00,0x00,0x04,0x02,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//^ 62 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,//_ 63 + 0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//` 64 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x19,0x24,0x22,0x22,0x22,0x3F,0x20,//a 65 + 0x08,0xF8,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,//b 66 + 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,//c 67 + 0x00,0x00,0x00,0x80,0x80,0x88,0xF8,0x00,0x00,0x0E,0x11,0x20,0x20,0x10,0x3F,0x20,//d 68 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x22,0x13,0x00,//e 69 + 0x00,0x80,0x80,0xF0,0x88,0x88,0x88,0x18,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//f 70 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,//g 71 + 0x08,0xF8,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//h 72 + 0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//i 73 + 0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,//j 74 + 0x08,0xF8,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x02,0x2D,0x30,0x20,0x00,//k 75 + 0x00,0x08,0x08,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//l 76 + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,//m 77 + 0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//n 78 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//o 79 + 0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0xA1,0x20,0x20,0x11,0x0E,0x00,//p 80 + 0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0xA0,0xFF,0x80,//q 81 + 0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,//r 82 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,//s 83 + 0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x00,0x00,//t 84 + 0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,//u 85 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x01,0x0E,0x30,0x08,0x06,0x01,0x00,//v 86 + 0x80,0x80,0x00,0x80,0x00,0x80,0x80,0x80,0x0F,0x30,0x0C,0x03,0x0C,0x30,0x0F,0x00,//w 87 + 0x00,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x31,0x2E,0x0E,0x31,0x20,0x00,//x 88 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x80,0x81,0x8E,0x70,0x18,0x06,0x01,0x00,//y 89 + 0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,//z 90 + 0x00,0x00,0x00,0x00,0x80,0x7C,0x02,0x02,0x00,0x00,0x00,0x00,0x00,0x3F,0x40,0x40,//{ 91 + 0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,//| 92 + 0x00,0x02,0x02,0x7C,0x80,0x00,0x00,0x00,0x00,0x40,0x40,0x3F,0x00,0x00,0x00,0x00,//} 93 + 0x00,0x06,0x01,0x01,0x02,0x02,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//~ 94 +}; + + +unsigned char Aciss_8X16[]={ +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*" ",0*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x00,/*"!",1*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x0C,0x02,0x10,0x0C,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*""",2*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0xC0,0x78,0x40,0xC0,0x78,0x00,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x00,/*"#",3*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x88,0xFC,0x08,0x30,0x00,0x00,0x18,0x20,0x20,0xFF,0x21,0x1E,0x00,/*"$",4*/ +/* (8 X 16 , 宋体 )*/ + +0xF0,0x08,0xF0,0x80,0x60,0x18,0x00,0x00,0x00,0x31,0x0C,0x03,0x1E,0x21,0x1E,0x00,/*"%",5*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x2C,0x19,0x27,0x21,0x10,/*"&",6*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x12,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"'",7*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,/*"(",8*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,/*")",9*/ +/* (8 X 16 , 宋体 )*/ + +0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,/*"*",10*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x0F,0x01,0x01,0x01,/*"+",11*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x70,0x00,0x00,0x00,0x00,0x00,/*",",12*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x00,/*"-",13*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,/*".",14*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xC0,0x38,0x04,0x00,0x00,0x60,0x18,0x07,0x00,0x00,0x00,0x00,/*"/",15*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,/*"0",16*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,/*"1",17*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x08,0x08,0x08,0x08,0xF0,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,/*"2",18*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x30,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x18,0x20,0x21,0x21,0x22,0x1C,0x00,/*"3",19*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x30,0xF8,0x00,0x00,0x00,0x06,0x05,0x24,0x24,0x3F,0x24,0x24,/*"4",20*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF8,0x88,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x20,0x20,0x20,0x11,0x0E,0x00,/*"5",21*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x88,0x88,0x90,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x20,0x1F,0x00,/*"6",22*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x18,0x08,0x08,0x88,0x68,0x18,0x00,0x00,0x00,0x00,0x3E,0x01,0x00,0x00,0x00,/*"7",23*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,/*"8",24*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x08,0x08,0x10,0xE0,0x00,0x00,0x01,0x12,0x22,0x22,0x11,0x0F,0x00,/*"9",25*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,/*":",26*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,/*";",27*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,/*"<",28*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00,/*"=",29*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,/*">",30*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x48,0x08,0x08,0x88,0x70,0x00,0x00,0x00,0x00,0x30,0x37,0x00,0x00,0x00,/*"?",31*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x28,0x2F,0x28,0x17,0x00,/*"@",32*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,/*"A",33*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,/*"B",34*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,/*"C",35*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,/*"D",36*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,/*"E",37*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,/*"F",38*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,/*"G",39*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,/*"H",40*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"I",41*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,/*"J",42*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,/*"K",43*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,/*"L",44*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x01,0x3E,0x01,0x3F,0x20,0x00,/*"M",45*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,/*"N",46*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,/*"O",47*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,/*"P",48*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x28,0x28,0x30,0x50,0x4F,0x00,/*"Q",49*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,/*"R",50*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",51*/ +/* (8 X 16 , 宋体 )*/ + +0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"T",52*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"U",53*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,/*"V",54*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x00,0xF8,0x00,0xF8,0x08,0x00,0x00,0x03,0x3E,0x01,0x3E,0x03,0x00,0x00,/*"W",55*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",56*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"Y",57*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,/*"Z",58*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,/*"[",59*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x04,0x38,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,/*"\",60*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,/*"]",61*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x04,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"^",62*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,/*"_",63*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"`",64*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x19,0x24,0x24,0x12,0x3F,0x20,0x00,/*"a",65*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,/*"b",66*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,/*"c",67*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x90,0xF0,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"d",68*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x24,0x24,0x24,0x24,0x17,0x00,/*"e",69*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x90,0x90,0x20,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"f",70*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,/*"g",71*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"h",72*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"i",73*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,/*"j",74*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x06,0x29,0x30,0x20,0x00,/*"k",75*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"l",76*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,/*"m",77*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"n",78*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"o",79*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0x91,0x20,0x20,0x11,0x0E,0x00,/*"p",80*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x00,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0x91,0xFF,0x80,/*"q",81*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,/*"r",82*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,/*"s",83*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x10,0x00,/*"t",84*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"u",85*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x03,0x0C,0x30,0x0C,0x03,0x00,0x00,/*"v",86*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x80,0x80,0x01,0x0E,0x30,0x0C,0x07,0x38,0x06,0x01,/*"w",87*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x20,0x31,0x0E,0x2E,0x31,0x20,0x00,/*"x",88*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x81,0x86,0x78,0x18,0x06,0x01,0x00,/*"y",89*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,/*"z",90*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0xFC,0x02,0x02,0x00,0x00,0x00,0x00,0x01,0x3E,0x40,0x40,/*"{",91*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,/*"|",92*/ +/* (8 X 16 , 宋体 )*/ + +0x02,0x02,0xFC,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x3E,0x01,0x00,0x00,0x00,0x00,/*"}",93*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x01,0x02,0x02,0x04,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"~",94*/ +/* (8 X 16 , 宋体 )*/ + +}; +//确定汉字字模数据位置 +const unsigned char indexs[][2]={"基","于","海","思","单","片","机","智","能","中","专","速","度","一", +"二","三","四","五","档","位","电"}; + + +const unsigned char Hzk[][32]={ +{0x00,0x04,0x04,0x04,0xFF,0x54,0x54,0x54,0x54,0x54,0xFF,0x04,0x04,0x04,0x00,0x00}, +{0x11,0x11,0x89,0x85,0x93,0x91,0x91,0xFD,0x91,0x91,0x93,0x85,0x89,0x11,0x11,0x00},/*"基",0*/ +{0x40,0x40,0x42,0x42,0x42,0x42,0x42,0xFE,0x42,0x42,0x42,0x42,0x42,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x40,0x80,0x7F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"于",1*/ +{0x10,0x60,0x02,0x0C,0xC0,0x10,0x08,0xF7,0x14,0x54,0x94,0x14,0xF4,0x04,0x00,0x00}, +{0x04,0x04,0x7C,0x03,0x00,0x01,0x1D,0x13,0x11,0x55,0x99,0x51,0x3F,0x11,0x01,0x00},/*"海",2*/ +{0x00,0x00,0xFE,0x92,0x92,0x92,0x92,0xFE,0x92,0x92,0x92,0x92,0xFE,0x00,0x00,0x00}, +{0x40,0x38,0x01,0x00,0x3C,0x40,0x40,0x42,0x4C,0x40,0x40,0x70,0x05,0x08,0x30,0x00},/*"思",3*/ +{0x00,0x00,0xF8,0x49,0x4A,0x4C,0x48,0xF8,0x48,0x4C,0x4A,0x49,0xF8,0x00,0x00,0x00}, +{0x10,0x10,0x13,0x12,0x12,0x12,0x12,0xFF,0x12,0x12,0x12,0x12,0x13,0x10,0x10,0x00},/*"单",4*/ +{0x00,0x00,0x00,0xFE,0x20,0x20,0x20,0x20,0x20,0x3F,0x20,0x20,0x20,0x20,0x00,0x00}, +{0x00,0x80,0x60,0x1F,0x02,0x02,0x02,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x00},/*"片",5*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x00,0xFE,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x83,0x60,0x1F,0x00,0x00,0x00,0x3F,0x40,0x40,0x78,0x00},/*"机",6*/ +{0x10,0x94,0x53,0x32,0x1E,0x32,0x52,0x10,0x00,0x7E,0x42,0x42,0x42,0x7E,0x00,0x00}, +{0x00,0x00,0x00,0xFF,0x49,0x49,0x49,0x49,0x49,0x49,0x49,0xFF,0x00,0x00,0x00,0x00},/*"智",7*/ +{0x08,0xCC,0x4A,0x49,0x48,0x4A,0xCC,0x18,0x00,0x7F,0x88,0x88,0x84,0x82,0xE0,0x00}, +{0x00,0xFF,0x12,0x12,0x52,0x92,0x7F,0x00,0x00,0x7E,0x88,0x88,0x84,0x82,0xE0,0x00},/*"能",8*/ +{0x00,0x00,0xF0,0x10,0x10,0x10,0x10,0xFF,0x10,0x10,0x10,0x10,0xF0,0x00,0x00,0x00}, +{0x00,0x00,0x0F,0x04,0x04,0x04,0x04,0xFF,0x04,0x04,0x04,0x04,0x0F,0x00,0x00,0x00},/*"中",9*/ +{0x40,0x40,0x48,0x48,0x48,0xC8,0x78,0x4F,0x48,0x48,0x48,0x48,0x48,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x03,0x12,0x12,0x22,0x22,0x52,0x8A,0x06,0x00,0x00,0x00,0x00},/*"专",10*/ + +{0x40,0x40,0x42,0xCC,0x00,0x04,0xF4,0x94,0x94,0xFF,0x94,0x94,0xF4,0x04,0x00,0x00}, +{0x00,0x40,0x20,0x1F,0x20,0x48,0x44,0x42,0x41,0x5F,0x41,0x42,0x44,0x48,0x40,0x00},/*"速",11*/ +{0x00,0x00,0xFC,0x24,0x24,0x24,0xFC,0x25,0x26,0x24,0xFC,0x24,0x24,0x24,0x04,0x00}, +{0x40,0x30,0x8F,0x80,0x84,0x4C,0x55,0x25,0x25,0x25,0x55,0x4C,0x80,0x80,0x80,0x00},/*"度",12*/ +{0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"一",13*/ +{0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,0x00}, +{0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x00},/*"二",14*/ +{0x00,0x04,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x04,0x00,0x00}, +{0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x00},/*"三",15*/ +{0x00,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x00,0x00}, +{0x00,0x7F,0x28,0x24,0x23,0x20,0x20,0x20,0x20,0x21,0x22,0x22,0x22,0x7F,0x00,0x00},/*"四",16*/ +{0x00,0x02,0x42,0x42,0x42,0xC2,0x7E,0x42,0x42,0x42,0x42,0xC2,0x02,0x02,0x00,0x00}, +{0x40,0x40,0x40,0x40,0x78,0x47,0x40,0x40,0x40,0x40,0x40,0x7F,0x40,0x40,0x40,0x00},/*"五",17*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x40,0x42,0x5C,0x40,0x7F,0x40,0x50,0xCE,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x01,0x40,0x44,0x44,0x44,0x44,0x44,0x44,0xFF,0x00,0x00},/*"档",18*/ +{0x00,0x80,0x60,0xF8,0x07,0x10,0x90,0x10,0x11,0x16,0x10,0x10,0xD0,0x10,0x00,0x00}, +{0x01,0x00,0x00,0xFF,0x40,0x40,0x41,0x5E,0x40,0x40,0x70,0x4E,0x41,0x40,0x40,0x00},/*"位",19*/ +{0x00,0x00,0xF8,0x88,0x88,0x88,0x88,0xFF,0x88,0x88,0x88,0x88,0xF8,0x00,0x00,0x00}, +{0x00,0x00,0x1F,0x08,0x08,0x08,0x08,0x7F,0x88,0x88,0x88,0x88,0x9F,0x80,0xF0,0x00},/*"电",20*/ + + + + +}; + + + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/src/oled.c b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/src/oled.c new file mode 100644 index 0000000000000000000000000000000000000000..6d3cc74d89ed838c67010f64e1df1094a46c5afe --- /dev/null +++ b/vendor/yibaina_3061M/mpu6050_oled_sample/user/oled/src/oled.c @@ -0,0 +1,412 @@ +#include "main.h" +#include "debug.h" +#include "oled_fonts.h" +#include "oled.h" +#include + +#define OLED_WRITE_REG 0x78 //0x78 ap3216 0x3C +#define OLED_READ_REG OLED_WRITE_REG+1 + +#define I2C_SAMPLE_OLED_PAGE_SIZE 7//一次写一个字节 +#define I2C_SAMPLE_OLED_ADDR_SIZE 1 +#define I2C_SAMPLE_MAX_TIMEOUT 10000 + + + + +/** + * @brief 在阻塞模式下读取数据 + * @param addr 要读取的寄存器地址 + * @param buffer 用于存储读取数据的缓冲区 + * @param length 要读取的数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Read(unsigned char addr, unsigned char *buffer, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 存储要读取的寄存器地址 + unsigned char tempAddr[I2C_SAMPLE_OLED_ADDR_SIZE]; + tempAddr[0] = addr; + + // 发送寄存器地址 + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempAddr, I2C_SAMPLE_OLED_ADDR_SIZE); + + // 发送寄存器地址是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + + /* 从设备读取数据 */ + ret = HAL_I2C_MasterReadDMA(&g_i2c0, OLED_READ_REG, buffer, length); + + // 从寄存器地址读取数据是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + return ret; +} + +/** + * @brief 在阻塞模式下写入数据 + * @param addr 寄存器地址 + * @param data 要写入的数据 + * @param length 数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Write(unsigned char addr, unsigned char data, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 使用两个字节的数组,存储写寄存器地址和发送数据 + unsigned char tempWrite[I2C_SAMPLE_OLED_PAGE_SIZE + I2C_SAMPLE_OLED_ADDR_SIZE]; + tempWrite[0] = addr; // 要写入的寄存器地址 + tempWrite[1] = data; // 要写入的数据 + + // 写入的寄存器地址长度+写入的数据长度(2字节) + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempWrite, I2C_SAMPLE_OLED_ADDR_SIZE + length); + + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Write Data Fail!,ret:%d\r\n", __LINE__, ret); + } + return ret; +} + +// OLED屏幕初始化 +void OLED_Init(void) +{ + BASE_FUNC_DELAY_MS(100); + I2C_Write(0x00, 0xAE, 1); // 关闭显示 + I2C_Write(0x00, 0x00, 1); // 设置低列地址 + I2C_Write(0x00, 0x10, 1); // 设置高列地址 + I2C_Write(0x00, 0x40, 1); // 设置起始行地址 + I2C_Write(0x00, 0xB0, 1); // 设置页面寻址模式的起始页地址,0-7 + I2C_Write(0x00, 0x81, 1); // 设置对比度控制寄存器 + I2C_Write(0x00, 0xFF, 1); // 对比度调节 0x00~0xff + I2C_Write(0x00, 0xA1, 1); // 设置段重映射 0 到 127 + I2C_Write(0x00, 0xA6, 1); // 设置正常显示 + I2C_Write(0x00, 0xA8, 1); // 设置多重扫描比率(1 到 64) + I2C_Write(0x00, 0x3F, 1); // 设置多重扫描比率的具体值 + I2C_Write(0x00, 0xC8, 1); // 设置COM输出扫描方向 + I2C_Write(0x00, 0xD3, 1); // 设置显示偏移 + I2C_Write(0x00, 0x00, 1); // 不偏移 + I2C_Write(0x00, 0xD5, 1); // 设置显示时钟分频比/振荡器频率 + I2C_Write(0x00, 0x80, 1); // 设置分频比 + I2C_Write(0x00, 0xD8, 1); // 设置预充电周期 + I2C_Write(0x00, 0x05, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xD9, 1); // 设置预充电周期 + I2C_Write(0x00, 0xF1, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xDA, 1); // 设置COM引脚硬件配置 + I2C_Write(0x00, 0x12, 1); // 设置COM引脚硬件配置的具体值 + I2C_Write(0x00, 0xDB, 1); // 设置VCOMH + I2C_Write(0x00, 0x30, 1); // 设置VCOMH的具体值 0x20, 0.77xVcc + I2C_Write(0x00, 0x8D, 1); // 设置DC-DC使能 + I2C_Write(0x00, 0x14, 1); // 设置DC-DC使能的具体值 + I2C_Write(0x00, 0xAF, 1); // 打开OLED面板 + OLED_Clear(); // 清屏 +} + +// 写命令 +void OLED_WriteCommand(unsigned char dat){ + I2C_Write(0x00,dat,1); +} + +// 写数据 +void OLED_WriteData(unsigned char dat){ + I2C_Write(0x40,dat,1); +} + +// 区别是写数据还是写命令 +void OLED_Write_DataOrCommand(unsigned dat,unsigned cmd) +{ + if(cmd){ + OLED_WriteData(dat); + } + else{ + OLED_WriteCommand(dat); + } +} + +// 清屏 +void OLED_Clear(void) +{ + unsigned char i, n; + for (i = 0; i < 8; i++) + { + OLED_Write_DataOrCommand(0xb0 + i, OLED_CMD); // 设置页地址(0~7) + OLED_Write_DataOrCommand(0x02, OLED_CMD); // 设置显示位置—列低地址 0x00 + OLED_Write_DataOrCommand(0x10, OLED_CMD); // 设置显示位置—列高地址 + for (n = 0; n < 128; n++) + OLED_Write_DataOrCommand(0, OLED_DATA); + } // 更新显示 +} + +// 开启OLED +void OLED_Display_On(void) +{ + OLED_Write_DataOrCommand(0X8D, OLED_CMD); // 设置电荷泵 + OLED_Write_DataOrCommand(0X14, OLED_CMD); // 开启电荷泵 + OLED_Write_DataOrCommand(0XAF, OLED_CMD); // OLED唤醒 +} + +// 设置起始点坐标 +void OLED_Set_Pos(unsigned char x, unsigned char y) +{ + OLED_Write_DataOrCommand(0xb0 + y, OLED_CMD); + OLED_Write_DataOrCommand((((x + 2) & 0xf0) >> 4) | 0x10, OLED_CMD); // 取高位 + OLED_Write_DataOrCommand(((x + 2) & 0x0f), OLED_CMD); // 取低位 +} + +// 显示字符 +void OLED_ShowChar(unsigned char x,unsigned char y,unsigned char chr,unsigned char Char_Size) +{ + unsigned char c = 0, i = 0; + c = chr - ' '; // 得到偏移后的值 + if (x > Max_Column - 1) + { + x = 0; + y = y + 2; + } + if (Char_Size == 16) + { + OLED_Set_Pos(x, y); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i], OLED_DATA); + OLED_Set_Pos(x, y + 1); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i + 8], OLED_DATA); + } + else + { + OLED_Set_Pos(x, y); + for (i = 0; i < 6; i++) + OLED_Write_DataOrCommand(F6x8[c][i], OLED_DATA); + } +} + + + +void OLED_displaychar(unsigned char col,unsigned char page,unsigned char eng) +{ + unsigned char font_res=0; + + font_res=eng-' '; //在ACISS的第几次位 + + for(unsigned char i=0;i<2;i++) + { + //设置显示位置 + OLED_WriteCommand(0x00 + (col & 0x0f));//设置低位列地址 + OLED_WriteCommand(0x10 + ((col & 0xf0)>>4));//设置高位列地址 + OLED_WriteCommand(0xb0+page+i);//设置页地址 + for(unsigned char j=0;j<8;j++) + { + OLED_WriteData(Aciss_8X16[16*font_res+8*i+j]); + } + } +} + + + +//显示2个数字 +//x,y :起点坐标 +//len :数字的位数 +//size:字体大小 +//mode:模式 0,填充模式;1,叠加模式 +//num:数值(0~4294967295); + +// void OLED_ShowNum(unsigned char x,unsigned char y,int num,unsigned char len,unsigned char size2) +// { +// unsigned char t,temp; +// unsigned char enshow = 0; +// for (t = 0; t < len; t++) +// { +// temp = (num / oled_pow(10, len - t - 1)) % 10; // 根据位数来显示数字 +// if (enshow == 0 && t < (len - 1)) +// { +// if (temp == 0) +// { +// OLED_ShowChar(x + (size2)*t, y, ' ', size2); +// continue; +// } +// else +// enshow = 1; +// } +// OLED_ShowChar(x + (size2)*t, y, temp + '0', size2); // ? +// } +// } + +/** + * @brief 在OLED上显示数字(支持负数) + * @param x: 起始列坐标 (0~127) + * @param y: 起始行坐标 (0~7) + * @param num: 要显示的数字(支持有符号整数) + * @param len: 数字总显示位数(包括符号位) + * @param size2: 字体大小倍数(通常为8或16的倍数) + * @note 自动处理负数,正数不显示符号位 + */ +void OLED_ShowNum(unsigned char x, unsigned char y, int num, unsigned char len, unsigned char size2) +{ + unsigned char t, temp; + unsigned char enshow = 0; + unsigned char is_negative = 0; + + // 处理负数 + if (num < 0) { + is_negative = 1; + num = -num; // 转换为正数处理 + len--; // 符号位占用一个显示位 + } + + for (t = 0; t < len; t++) + { + temp = (num / oled_pow(10, len - t - 1)) % 10; // 提取当前位数 + + // 前导零处理(跳过无效零) + if (enshow == 0 && t < (len - 1)) { + if (temp == 0) { + // 如果是符号位后的第一个有效位之前,显示空格 + if (is_negative && t == 0) { + OLED_ShowChar(x, y, '-', size2); // 显示负号 + x += size2; // 调整X坐标 + } else { + OLED_ShowChar(x + size2 * t, y, ' ', size2); + } + continue; + } else { + enshow = 1; // 遇到第一个非零数字,开始显示 + + // 如果数字为负且未显示符号,先显示负号 + if (is_negative) { + OLED_ShowChar(x, y, '-', size2); + x += size2; // 调整X坐标 + } + } + } + + // 显示当前数字 + OLED_ShowChar(x + size2 * t, y, temp + '0', size2); + } + + // 特殊情况处理:数字为0时 + if (num == 0) { + OLED_ShowChar(x + size2 * (len - 1), y, '0', size2); + } +} + + + + +//显示一个字符号串 +void OLED_ShowString(unsigned char x,unsigned char y,char *chr,unsigned char Char_Size) +{ + unsigned char j = 0; + while (chr[j] != '\0') + { + OLED_ShowChar(x, y, chr[j], Char_Size); + x += 8; + if (x > 120) +{ + x = 0; + y += 2; + } + j++; + } +} + + + + + +void OLED_displaychina(unsigned char x,unsigned char y,unsigned char *ch) +{ + int t,adder=0; + unsigned char k; + //确定汉字在小字库的位置 + for(k=0;k< sizeof(indexs) /sizeof(indexs[0]);k++) + { + if(*ch == indexs[k][0] && *(ch+1)==indexs[k][1]) + break; + } + + OLED_Set_Pos(x,y); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k][t],OLED_DATA); + adder+=1; + } + OLED_Set_Pos(x,y+1); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k+1][t],OLED_DATA); + adder+=1; + } + + +} + +/* +Function name: OLED_displaystr +Description:OLED显字符串 +param: u8 col 列位置 + u8 page 行位置 + u8 *str 字符串 +retval: void +Remarks: + + +*/ + + +void OLED_displaystr(unsigned char col,unsigned char page,unsigned char *str) +{ + while(*str !='\0') + { + if(*str >= 0xA1)//显示汉字 + { + OLED_displaychina(col,page,str); + str+=3; + col+=16; + } + else//显示英文 + { + OLED_displaychar(col,page,*str); + str+=1; + col+=8; + } + + } +} + + + + + +// /***********功能描述:显示显示BMP图片128×64起始点坐标(x,y),x的范围0~127,y为页的范围0~7*****************/ +// void OLED_DrawBMP(unsigned char x0, unsigned char y0,unsigned char x1, unsigned char y1,unsigned char BMP[]) +// { +// unsigned int j=0; +// unsigned char x,y; + +// if(y1%8==0) y=y1/8; +// else y=y1/8+1; +// for(y=y0;y +{0x00, 0x02, 0x01, 0x51, 0x09, 0x06},// ? +{0x00, 0x32, 0x49, 0x59, 0x51, 0x3E},// @ +{0x00, 0x7C, 0x12, 0x11, 0x12, 0x7C},// A +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x36},// B +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x22},// C +{0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C},// D +{0x00, 0x7F, 0x49, 0x49, 0x49, 0x41},// E +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x01},// F +{0x00, 0x3E, 0x41, 0x49, 0x49, 0x7A},// G +{0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F},// H +{0x00, 0x00, 0x41, 0x7F, 0x41, 0x00},// I +{0x00, 0x20, 0x40, 0x41, 0x3F, 0x01},// J +{0x00, 0x7F, 0x08, 0x14, 0x22, 0x41},// K +{0x00, 0x7F, 0x40, 0x40, 0x40, 0x40},// L +{0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F},// M +{0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F},// N +{0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E},// O +{0x00, 0x7F, 0x09, 0x09, 0x09, 0x06},// P +{0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E},// Q +{0x00, 0x7F, 0x09, 0x19, 0x29, 0x46},// R +{0x00, 0x46, 0x49, 0x49, 0x49, 0x31},// S +{0x00, 0x01, 0x01, 0x7F, 0x01, 0x01},// T +{0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F},// U +{0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F},// V +{0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F},// W +{0x00, 0x63, 0x14, 0x08, 0x14, 0x63},// X +{0x00, 0x07, 0x08, 0x70, 0x08, 0x07},// Y +{0x00, 0x61, 0x51, 0x49, 0x45, 0x43},// Z +{0x00, 0x00, 0x7F, 0x41, 0x41, 0x00},// [ +{0x00, 0x55, 0x2A, 0x55, 0x2A, 0x55},// 55 +{0x00, 0x00, 0x41, 0x41, 0x7F, 0x00},// ] +{0x00, 0x04, 0x02, 0x01, 0x02, 0x04},// ^ +{0x00, 0x40, 0x40, 0x40, 0x40, 0x40},// _ +{0x00, 0x00, 0x01, 0x02, 0x04, 0x00},// ' +{0x00, 0x20, 0x54, 0x54, 0x54, 0x78},// a +{0x00, 0x7F, 0x48, 0x44, 0x44, 0x38},// b +{0x00, 0x38, 0x44, 0x44, 0x44, 0x20},// c +{0x00, 0x38, 0x44, 0x44, 0x48, 0x7F},// d +{0x00, 0x38, 0x54, 0x54, 0x54, 0x18},// e +{0x00, 0x08, 0x7E, 0x09, 0x01, 0x02},// f +{0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C},// g +{0x00, 0x7F, 0x08, 0x04, 0x04, 0x78},// h +{0x00, 0x00, 0x44, 0x7D, 0x40, 0x00},// i +{0x00, 0x40, 0x80, 0x84, 0x7D, 0x00},// j +{0x00, 0x7F, 0x10, 0x28, 0x44, 0x00},// k +{0x00, 0x00, 0x41, 0x7F, 0x40, 0x00},// l +{0x00, 0x7C, 0x04, 0x18, 0x04, 0x78},// m +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x78},// n +{0x00, 0x38, 0x44, 0x44, 0x44, 0x38},// o +{0x00, 0xFC, 0x24, 0x24, 0x24, 0x18},// p +{0x00, 0x18, 0x24, 0x24, 0x18, 0xFC},// q +{0x00, 0x7C, 0x08, 0x04, 0x04, 0x08},// r +{0x00, 0x48, 0x54, 0x54, 0x54, 0x20},// s +{0x00, 0x04, 0x3F, 0x44, 0x40, 0x20},// t +{0x00, 0x3C, 0x40, 0x40, 0x20, 0x7C},// u +{0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C},// v +{0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C},// w +{0x00, 0x44, 0x28, 0x10, 0x28, 0x44},// x +{0x00, 0x1C, 0xA0, 0xA0, 0xA0, 0x7C},// y +{0x00, 0x44, 0x64, 0x54, 0x4C, 0x44},// z +{0x14, 0x14, 0x14, 0x14, 0x14, 0x14},// horiz lines +}; + +/****************************************8*16的点阵************************************/ +const unsigned char F8X16[]={ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,// 0 + 0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x00,//! 1 + 0x00,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//" 2 + 0x40,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x00,//# 3 + 0x00,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x00,//$ 4 + 0xF0,0x08,0xF0,0x00,0xE0,0x18,0x00,0x00,0x00,0x21,0x1C,0x03,0x1E,0x21,0x1E,0x00,//% 5 + 0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x24,0x19,0x27,0x21,0x10,//& 6 + 0x10,0x16,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//' 7 + 0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,//( 8 + 0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,//) 9 + 0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,//* 10 + 0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x1F,0x01,0x01,0x01,0x00,//+ 11 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xB0,0x70,0x00,0x00,0x00,0x00,0x00,//, 12 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,//- 13 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,//. 14 + 0x00,0x00,0x00,0x00,0x80,0x60,0x18,0x04,0x00,0x60,0x18,0x06,0x01,0x00,0x00,0x00,/// 15 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,//0 16 + 0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//1 17 + 0x00,0x70,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,//2 18 + 0x00,0x30,0x08,0x88,0x88,0x48,0x30,0x00,0x00,0x18,0x20,0x20,0x20,0x11,0x0E,0x00,//3 19 + 0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00,//4 20 + 0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00,//5 21 + 0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00,//6 22 + 0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00,//7 23 + 0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,//8 24 + 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x00,0x31,0x22,0x22,0x11,0x0F,0x00,//9 25 + 0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,//: 26 + 0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x00,0x00,0x00,0x00,//; 27 + 0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,//< 28 + 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x00,//= 29 + 0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,//> 30 + 0x00,0x70,0x48,0x08,0x08,0x08,0xF0,0x00,0x00,0x00,0x00,0x30,0x36,0x01,0x00,0x00,//? 31 + 0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x24,0x23,0x14,0x0B,0x00,//@ 32 + 0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,//A 33 + 0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,//B 34 + 0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,//C 35 + 0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,//D 36 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,//E 37 + 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,//F 38 + 0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,//G 39 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,//H 40 + 0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//I 41 + 0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,//J 42 + 0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,//K 43 + 0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,//L 44 + 0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x00,0x3F,0x00,0x3F,0x20,0x00,//M 45 + 0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,//N 46 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,//O 47 + 0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,//P 48 + 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x18,0x24,0x24,0x38,0x50,0x4F,0x00,//Q 49 + 0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,//R 50 + 0x00,0x70,0x88,0x08,0x08,0x08,0x38,0x00,0x00,0x38,0x20,0x21,0x21,0x22,0x1C,0x00,//S 51 + 0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//T 52 + 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//U 53 + 0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,//V 54 + 0xF8,0x08,0x00,0xF8,0x00,0x08,0xF8,0x00,0x03,0x3C,0x07,0x00,0x07,0x3C,0x03,0x00,//W 55 + 0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,//X 56 + 0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//Y 57 + 0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,//Z 58 + 0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,//[ 59 + 0x00,0x0C,0x30,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,//\ 60 + 0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,//] 61 + 0x00,0x00,0x04,0x02,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//^ 62 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,//_ 63 + 0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//` 64 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x19,0x24,0x22,0x22,0x22,0x3F,0x20,//a 65 + 0x08,0xF8,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,//b 66 + 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,//c 67 + 0x00,0x00,0x00,0x80,0x80,0x88,0xF8,0x00,0x00,0x0E,0x11,0x20,0x20,0x10,0x3F,0x20,//d 68 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x22,0x13,0x00,//e 69 + 0x00,0x80,0x80,0xF0,0x88,0x88,0x88,0x18,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//f 70 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,//g 71 + 0x08,0xF8,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//h 72 + 0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//i 73 + 0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,//j 74 + 0x08,0xF8,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x02,0x2D,0x30,0x20,0x00,//k 75 + 0x00,0x08,0x08,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//l 76 + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,//m 77 + 0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//n 78 + 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//o 79 + 0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0xA1,0x20,0x20,0x11,0x0E,0x00,//p 80 + 0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0xA0,0xFF,0x80,//q 81 + 0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,//r 82 + 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,//s 83 + 0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x00,0x00,//t 84 + 0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,//u 85 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x01,0x0E,0x30,0x08,0x06,0x01,0x00,//v 86 + 0x80,0x80,0x00,0x80,0x00,0x80,0x80,0x80,0x0F,0x30,0x0C,0x03,0x0C,0x30,0x0F,0x00,//w 87 + 0x00,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x31,0x2E,0x0E,0x31,0x20,0x00,//x 88 + 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x80,0x81,0x8E,0x70,0x18,0x06,0x01,0x00,//y 89 + 0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,//z 90 + 0x00,0x00,0x00,0x00,0x80,0x7C,0x02,0x02,0x00,0x00,0x00,0x00,0x00,0x3F,0x40,0x40,//{ 91 + 0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,//| 92 + 0x00,0x02,0x02,0x7C,0x80,0x00,0x00,0x00,0x00,0x40,0x40,0x3F,0x00,0x00,0x00,0x00,//} 93 + 0x00,0x06,0x01,0x01,0x02,0x02,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//~ 94 +}; + + +unsigned char Aciss_8X16[]={ +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*" ",0*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x00,/*"!",1*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x0C,0x02,0x10,0x0C,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*""",2*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0xC0,0x78,0x40,0xC0,0x78,0x00,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x00,/*"#",3*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x88,0xFC,0x08,0x30,0x00,0x00,0x18,0x20,0x20,0xFF,0x21,0x1E,0x00,/*"$",4*/ +/* (8 X 16 , 宋体 )*/ + +0xF0,0x08,0xF0,0x80,0x60,0x18,0x00,0x00,0x00,0x31,0x0C,0x03,0x1E,0x21,0x1E,0x00,/*"%",5*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x2C,0x19,0x27,0x21,0x10,/*"&",6*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x12,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"'",7*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,/*"(",8*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,/*")",9*/ +/* (8 X 16 , 宋体 )*/ + +0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,/*"*",10*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x0F,0x01,0x01,0x01,/*"+",11*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x70,0x00,0x00,0x00,0x00,0x00,/*",",12*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x00,/*"-",13*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,/*".",14*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xC0,0x38,0x04,0x00,0x00,0x60,0x18,0x07,0x00,0x00,0x00,0x00,/*"/",15*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,/*"0",16*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,/*"1",17*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x08,0x08,0x08,0x08,0xF0,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,/*"2",18*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x30,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x18,0x20,0x21,0x21,0x22,0x1C,0x00,/*"3",19*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x30,0xF8,0x00,0x00,0x00,0x06,0x05,0x24,0x24,0x3F,0x24,0x24,/*"4",20*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF8,0x88,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x20,0x20,0x20,0x11,0x0E,0x00,/*"5",21*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xE0,0x10,0x88,0x88,0x90,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x20,0x1F,0x00,/*"6",22*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x18,0x08,0x08,0x88,0x68,0x18,0x00,0x00,0x00,0x00,0x3E,0x01,0x00,0x00,0x00,/*"7",23*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,/*"8",24*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0xF0,0x08,0x08,0x08,0x10,0xE0,0x00,0x00,0x01,0x12,0x22,0x22,0x11,0x0F,0x00,/*"9",25*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,/*":",26*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,/*";",27*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,/*"<",28*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00,/*"=",29*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,/*">",30*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x70,0x48,0x08,0x08,0x88,0x70,0x00,0x00,0x00,0x00,0x30,0x37,0x00,0x00,0x00,/*"?",31*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x28,0x2F,0x28,0x17,0x00,/*"@",32*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,/*"A",33*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,/*"B",34*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,/*"C",35*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,/*"D",36*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,/*"E",37*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,/*"F",38*/ +/* (8 X 16 , 宋体 )*/ + +0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,/*"G",39*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,/*"H",40*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"I",41*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,/*"J",42*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,/*"K",43*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,/*"L",44*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x01,0x3E,0x01,0x3F,0x20,0x00,/*"M",45*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,/*"N",46*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,/*"O",47*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,/*"P",48*/ +/* (8 X 16 , 宋体 )*/ + +0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x28,0x28,0x30,0x50,0x4F,0x00,/*"Q",49*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,/*"R",50*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",51*/ +/* (8 X 16 , 宋体 )*/ + +0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"T",52*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"U",53*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,/*"V",54*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0xF8,0x00,0xF8,0x00,0xF8,0x08,0x00,0x00,0x03,0x3E,0x01,0x3E,0x03,0x00,0x00,/*"W",55*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,/*"X",56*/ +/* (8 X 16 , 宋体 )*/ + +0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,/*"Y",57*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,/*"Z",58*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,/*"[",59*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x04,0x38,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,/*"\",60*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,/*"]",61*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x04,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"^",62*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,/*"_",63*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"`",64*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x19,0x24,0x24,0x12,0x3F,0x20,0x00,/*"a",65*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,/*"b",66*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,/*"c",67*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x90,0xF0,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"d",68*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x24,0x24,0x24,0x24,0x17,0x00,/*"e",69*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x90,0x90,0x20,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"f",70*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,/*"g",71*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"h",72*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"i",73*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,/*"j",74*/ +/* (8 X 16 , 宋体 )*/ + +0x10,0xF0,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x06,0x29,0x30,0x20,0x00,/*"k",75*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,/*"l",76*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,/*"m",77*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,/*"n",78*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,/*"o",79*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0x91,0x20,0x20,0x11,0x0E,0x00,/*"p",80*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x80,0x80,0x00,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0x91,0xFF,0x80,/*"q",81*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,/*"r",82*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,/*"s",83*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x10,0x00,/*"t",84*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,/*"u",85*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x03,0x0C,0x30,0x0C,0x03,0x00,0x00,/*"v",86*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x00,0x80,0x80,0x00,0x80,0x80,0x01,0x0E,0x30,0x0C,0x07,0x38,0x06,0x01,/*"w",87*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x20,0x31,0x0E,0x2E,0x31,0x20,0x00,/*"x",88*/ +/* (8 X 16 , 宋体 )*/ + +0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x81,0x86,0x78,0x18,0x06,0x01,0x00,/*"y",89*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,/*"z",90*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0x00,0xFC,0x02,0x02,0x00,0x00,0x00,0x00,0x01,0x3E,0x40,0x40,/*"{",91*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,/*"|",92*/ +/* (8 X 16 , 宋体 )*/ + +0x02,0x02,0xFC,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x3E,0x01,0x00,0x00,0x00,0x00,/*"}",93*/ +/* (8 X 16 , 宋体 )*/ + +0x00,0x02,0x01,0x02,0x02,0x04,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,/*"~",94*/ +/* (8 X 16 , 宋体 )*/ + +}; +//确定汉字字模数据位置 +const unsigned char indexs[][2]={"基","于","海","思","单","片","机","智","能","中","专","速","度","一", +"二","三","四","五","档","位","电"}; + + +const unsigned char Hzk[][32]={ +{0x00,0x04,0x04,0x04,0xFF,0x54,0x54,0x54,0x54,0x54,0xFF,0x04,0x04,0x04,0x00,0x00}, +{0x11,0x11,0x89,0x85,0x93,0x91,0x91,0xFD,0x91,0x91,0x93,0x85,0x89,0x11,0x11,0x00},/*"基",0*/ +{0x40,0x40,0x42,0x42,0x42,0x42,0x42,0xFE,0x42,0x42,0x42,0x42,0x42,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x40,0x80,0x7F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"于",1*/ +{0x10,0x60,0x02,0x0C,0xC0,0x10,0x08,0xF7,0x14,0x54,0x94,0x14,0xF4,0x04,0x00,0x00}, +{0x04,0x04,0x7C,0x03,0x00,0x01,0x1D,0x13,0x11,0x55,0x99,0x51,0x3F,0x11,0x01,0x00},/*"海",2*/ +{0x00,0x00,0xFE,0x92,0x92,0x92,0x92,0xFE,0x92,0x92,0x92,0x92,0xFE,0x00,0x00,0x00}, +{0x40,0x38,0x01,0x00,0x3C,0x40,0x40,0x42,0x4C,0x40,0x40,0x70,0x05,0x08,0x30,0x00},/*"思",3*/ +{0x00,0x00,0xF8,0x49,0x4A,0x4C,0x48,0xF8,0x48,0x4C,0x4A,0x49,0xF8,0x00,0x00,0x00}, +{0x10,0x10,0x13,0x12,0x12,0x12,0x12,0xFF,0x12,0x12,0x12,0x12,0x13,0x10,0x10,0x00},/*"单",4*/ +{0x00,0x00,0x00,0xFE,0x20,0x20,0x20,0x20,0x20,0x3F,0x20,0x20,0x20,0x20,0x00,0x00}, +{0x00,0x80,0x60,0x1F,0x02,0x02,0x02,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x00},/*"片",5*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x00,0xFE,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x83,0x60,0x1F,0x00,0x00,0x00,0x3F,0x40,0x40,0x78,0x00},/*"机",6*/ +{0x10,0x94,0x53,0x32,0x1E,0x32,0x52,0x10,0x00,0x7E,0x42,0x42,0x42,0x7E,0x00,0x00}, +{0x00,0x00,0x00,0xFF,0x49,0x49,0x49,0x49,0x49,0x49,0x49,0xFF,0x00,0x00,0x00,0x00},/*"智",7*/ +{0x08,0xCC,0x4A,0x49,0x48,0x4A,0xCC,0x18,0x00,0x7F,0x88,0x88,0x84,0x82,0xE0,0x00}, +{0x00,0xFF,0x12,0x12,0x52,0x92,0x7F,0x00,0x00,0x7E,0x88,0x88,0x84,0x82,0xE0,0x00},/*"能",8*/ +{0x00,0x00,0xF0,0x10,0x10,0x10,0x10,0xFF,0x10,0x10,0x10,0x10,0xF0,0x00,0x00,0x00}, +{0x00,0x00,0x0F,0x04,0x04,0x04,0x04,0xFF,0x04,0x04,0x04,0x04,0x0F,0x00,0x00,0x00},/*"中",9*/ +{0x40,0x40,0x48,0x48,0x48,0xC8,0x78,0x4F,0x48,0x48,0x48,0x48,0x48,0x40,0x40,0x00}, +{0x00,0x00,0x00,0x00,0x03,0x12,0x12,0x22,0x22,0x52,0x8A,0x06,0x00,0x00,0x00,0x00},/*"专",10*/ + +{0x40,0x40,0x42,0xCC,0x00,0x04,0xF4,0x94,0x94,0xFF,0x94,0x94,0xF4,0x04,0x00,0x00}, +{0x00,0x40,0x20,0x1F,0x20,0x48,0x44,0x42,0x41,0x5F,0x41,0x42,0x44,0x48,0x40,0x00},/*"速",11*/ +{0x00,0x00,0xFC,0x24,0x24,0x24,0xFC,0x25,0x26,0x24,0xFC,0x24,0x24,0x24,0x04,0x00}, +{0x40,0x30,0x8F,0x80,0x84,0x4C,0x55,0x25,0x25,0x25,0x55,0x4C,0x80,0x80,0x80,0x00},/*"度",12*/ +{0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"一",13*/ +{0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,0x00}, +{0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x00},/*"二",14*/ +{0x00,0x04,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x84,0x04,0x00,0x00}, +{0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x00},/*"三",15*/ +{0x00,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x04,0x04,0x04,0xFC,0x00,0x00}, +{0x00,0x7F,0x28,0x24,0x23,0x20,0x20,0x20,0x20,0x21,0x22,0x22,0x22,0x7F,0x00,0x00},/*"四",16*/ +{0x00,0x02,0x42,0x42,0x42,0xC2,0x7E,0x42,0x42,0x42,0x42,0xC2,0x02,0x02,0x00,0x00}, +{0x40,0x40,0x40,0x40,0x78,0x47,0x40,0x40,0x40,0x40,0x40,0x7F,0x40,0x40,0x40,0x00},/*"五",17*/ +{0x10,0x10,0xD0,0xFF,0x90,0x10,0x40,0x42,0x5C,0x40,0x7F,0x40,0x50,0xCE,0x00,0x00}, +{0x04,0x03,0x00,0xFF,0x00,0x01,0x40,0x44,0x44,0x44,0x44,0x44,0x44,0xFF,0x00,0x00},/*"档",18*/ +{0x00,0x80,0x60,0xF8,0x07,0x10,0x90,0x10,0x11,0x16,0x10,0x10,0xD0,0x10,0x00,0x00}, +{0x01,0x00,0x00,0xFF,0x40,0x40,0x41,0x5E,0x40,0x40,0x70,0x4E,0x41,0x40,0x40,0x00},/*"位",19*/ +{0x00,0x00,0xF8,0x88,0x88,0x88,0x88,0xFF,0x88,0x88,0x88,0x88,0xF8,0x00,0x00,0x00}, +{0x00,0x00,0x1F,0x08,0x08,0x08,0x08,0x7F,0x88,0x88,0x88,0x88,0x9F,0x80,0xF0,0x00},/*"电",20*/ + + + + +}; + + + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/oled_sample/user/oled/src/oled.c b/vendor/yibaina_3061M/oled_sample/user/oled/src/oled.c new file mode 100644 index 0000000000000000000000000000000000000000..355dd0d14c15bb5dab38017d6d7a36ebcfbdea70 --- /dev/null +++ b/vendor/yibaina_3061M/oled_sample/user/oled/src/oled.c @@ -0,0 +1,352 @@ +#include "main.h" +#include "debug.h" +#include "oled_fonts.h" +#include "oled.h" +#include + +#define OLED_WRITE_REG 0x78 //0x78 ap3216 0x3C +#define OLED_READ_REG OLED_WRITE_REG+1 + +#define I2C_SAMPLE_OLED_PAGE_SIZE 7//一次写一个字节 +#define I2C_SAMPLE_OLED_ADDR_SIZE 1 +#define I2C_SAMPLE_MAX_TIMEOUT 10000 + + + + +/** + * @brief 在阻塞模式下读取数据 + * @param addr 要读取的寄存器地址 + * @param buffer 用于存储读取数据的缓冲区 + * @param length 要读取的数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Read(unsigned char addr, unsigned char *buffer, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 存储要读取的寄存器地址 + unsigned char tempAddr[I2C_SAMPLE_OLED_ADDR_SIZE]; + tempAddr[0] = addr; + + // 发送寄存器地址 + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempAddr, I2C_SAMPLE_OLED_ADDR_SIZE); + + // 发送寄存器地址是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + + /* 从设备读取数据 */ + ret = HAL_I2C_MasterReadDMA(&g_i2c0, OLED_READ_REG, buffer, length); + + // 从寄存器地址读取数据是否成功 + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Read Data Fail,ret:%d\r\n", __LINE__, ret); + return ret; + } + return ret; +} + +/** + * @brief 在阻塞模式下写入数据 + * @param addr 寄存器地址 + * @param data 要写入的数据 + * @param length 数据长度 + * @retval BASE状态类型: OK, ERROR, BUSY, TIMEOUT, NOT SUPPORT + */ +BASE_StatusType I2C_Write(unsigned char addr, unsigned char data, unsigned int length) +{ + BASE_StatusType ret = BASE_STATUS_OK; + + // 使用两个字节的数组,存储写寄存器地址和发送数据 + unsigned char tempWrite[I2C_SAMPLE_OLED_PAGE_SIZE + I2C_SAMPLE_OLED_ADDR_SIZE]; + tempWrite[0] = addr; // 要写入的寄存器地址 + tempWrite[1] = data; // 要写入的数据 + + // 写入的寄存器地址长度+写入的数据长度(2字节) + ret = HAL_I2C_MasterWriteDMA(&g_i2c0, OLED_WRITE_REG, tempWrite, I2C_SAMPLE_OLED_ADDR_SIZE + length); + + if (ret != BASE_STATUS_OK){ + DBG_PRINTF("LINE:%d,Write Data Fail!,ret:%d\r\n", __LINE__, ret); + } + return ret; +} + +// OLED屏幕初始化 +void OLED_Init(void) +{ + BASE_FUNC_DELAY_MS(100); + I2C_Write(0x00, 0xAE, 1); // 关闭显示 + I2C_Write(0x00, 0x00, 1); // 设置低列地址 + I2C_Write(0x00, 0x10, 1); // 设置高列地址 + I2C_Write(0x00, 0x40, 1); // 设置起始行地址 + I2C_Write(0x00, 0xB0, 1); // 设置页面寻址模式的起始页地址,0-7 + I2C_Write(0x00, 0x81, 1); // 设置对比度控制寄存器 + I2C_Write(0x00, 0xFF, 1); // 对比度调节 0x00~0xff + I2C_Write(0x00, 0xA1, 1); // 设置段重映射 0 到 127 + I2C_Write(0x00, 0xA6, 1); // 设置正常显示 + I2C_Write(0x00, 0xA8, 1); // 设置多重扫描比率(1 到 64) + I2C_Write(0x00, 0x3F, 1); // 设置多重扫描比率的具体值 + I2C_Write(0x00, 0xC8, 1); // 设置COM输出扫描方向 + I2C_Write(0x00, 0xD3, 1); // 设置显示偏移 + I2C_Write(0x00, 0x00, 1); // 不偏移 + I2C_Write(0x00, 0xD5, 1); // 设置显示时钟分频比/振荡器频率 + I2C_Write(0x00, 0x80, 1); // 设置分频比 + I2C_Write(0x00, 0xD8, 1); // 设置预充电周期 + I2C_Write(0x00, 0x05, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xD9, 1); // 设置预充电周期 + I2C_Write(0x00, 0xF1, 1); // 设置预充电周期的具体值 + I2C_Write(0x00, 0xDA, 1); // 设置COM引脚硬件配置 + I2C_Write(0x00, 0x12, 1); // 设置COM引脚硬件配置的具体值 + I2C_Write(0x00, 0xDB, 1); // 设置VCOMH + I2C_Write(0x00, 0x30, 1); // 设置VCOMH的具体值 0x20, 0.77xVcc + I2C_Write(0x00, 0x8D, 1); // 设置DC-DC使能 + I2C_Write(0x00, 0x14, 1); // 设置DC-DC使能的具体值 + I2C_Write(0x00, 0xAF, 1); // 打开OLED面板 + OLED_Clear(); // 清屏 +} + +// 写命令 +void OLED_WriteCommand(unsigned char dat){ + I2C_Write(0x00,dat,1); +} + +// 写数据 +void OLED_WriteData(unsigned char dat){ + I2C_Write(0x40,dat,1); +} + +// 区别是写数据还是写命令 +void OLED_Write_DataOrCommand(unsigned dat,unsigned cmd) +{ + if(cmd){ + OLED_WriteData(dat); + } + else{ + OLED_WriteCommand(dat); + } +} + +// 清屏 +void OLED_Clear(void) +{ + unsigned char i, n; + for (i = 0; i < 8; i++) + { + OLED_Write_DataOrCommand(0xb0 + i, OLED_CMD); // 设置页地址(0~7) + OLED_Write_DataOrCommand(0x02, OLED_CMD); // 设置显示位置—列低地址 0x00 + OLED_Write_DataOrCommand(0x10, OLED_CMD); // 设置显示位置—列高地址 + for (n = 0; n < 128; n++) + OLED_Write_DataOrCommand(0, OLED_DATA); + } // 更新显示 +} + +// 开启OLED +void OLED_Display_On(void) +{ + OLED_Write_DataOrCommand(0X8D, OLED_CMD); // 设置电荷泵 + OLED_Write_DataOrCommand(0X14, OLED_CMD); // 开启电荷泵 + OLED_Write_DataOrCommand(0XAF, OLED_CMD); // OLED唤醒 +} + +// 设置起始点坐标 +void OLED_Set_Pos(unsigned char x, unsigned char y) +{ + OLED_Write_DataOrCommand(0xb0 + y, OLED_CMD); + OLED_Write_DataOrCommand((((x + 2) & 0xf0) >> 4) | 0x10, OLED_CMD); // 取高位 + OLED_Write_DataOrCommand(((x + 2) & 0x0f), OLED_CMD); // 取低位 +} + +// 显示字符 +void OLED_ShowChar(unsigned char x,unsigned char y,unsigned char chr,unsigned char Char_Size) +{ + unsigned char c = 0, i = 0; + c = chr - ' '; // 得到偏移后的值 + if (x > Max_Column - 1) + { + x = 0; + y = y + 2; + } + if (Char_Size == 16) + { + OLED_Set_Pos(x, y); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i], OLED_DATA); + OLED_Set_Pos(x, y + 1); + for (i = 0; i < 8; i++) + OLED_Write_DataOrCommand(F8X16[c * 16 + i + 8], OLED_DATA); + } + else + { + OLED_Set_Pos(x, y); + for (i = 0; i < 6; i++) + OLED_Write_DataOrCommand(F6x8[c][i], OLED_DATA); + } +} + + + +void OLED_displaychar(unsigned char col,unsigned char page,unsigned char eng) +{ + unsigned char font_res=0; + + font_res=eng-' '; //在ACISS的第几次位 + + for(unsigned char i=0;i<2;i++) + { + //设置显示位置 + OLED_WriteCommand(0x00 + (col & 0x0f));//设置低位列地址 + OLED_WriteCommand(0x10 + ((col & 0xf0)>>4));//设置高位列地址 + OLED_WriteCommand(0xb0+page+i);//设置页地址 + for(unsigned char j=0;j<8;j++) + { + OLED_WriteData(Aciss_8X16[16*font_res+8*i+j]); + } + } +} + + + +//显示2个数字 +//x,y :起点坐标 +//len :数字的位数 +//size:字体大小 +//mode:模式 0,填充模式;1,叠加模式 +//num:数值(0~4294967295); + +void OLED_ShowNum(unsigned char x,unsigned char y,unsigned int num,unsigned char len,unsigned char size2) +{ + unsigned char t,temp; + unsigned char enshow = 0; + for (t = 0; t < len; t++) + { + temp = (num / oled_pow(10, len - t - 1)) % 10; // 根据位数来显示数字 + if (enshow == 0 && t < (len - 1)) + { + if (temp == 0) + { + OLED_ShowChar(x + (size2)*t, y, ' ', size2); + continue; + } + else + enshow = 1; + } + OLED_ShowChar(x + (size2)*t, y, temp + '0', size2); // ? + } +} + + +//显示一个字符号串 +void OLED_ShowString(unsigned char x,unsigned char y,char *chr,unsigned char Char_Size) +{ + unsigned char j = 0; + while (chr[j] != '\0') + { + OLED_ShowChar(x, y, chr[j], Char_Size); + x += 8; + if (x > 120) +{ + x = 0; + y += 2; + } + j++; + } +} + + + + + +void OLED_displaychina(unsigned char x,unsigned char y,unsigned char *ch) +{ + int t,adder=0; + unsigned char k; + //确定汉字在小字库的位置 + for(k=0;k< sizeof(indexs) /sizeof(indexs[0]);k++) + { + if(*ch == indexs[k][0] && *(ch+1)==indexs[k][1]) + break; + } + + OLED_Set_Pos(x,y); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k][t],OLED_DATA); + adder+=1; + } + OLED_Set_Pos(x,y+1); + for(t=0;t<16;t++) + { + OLED_Write_DataOrCommand(Hzk[2*k+1][t],OLED_DATA); + adder+=1; + } + + +} + +/* +Function name: OLED_displaystr +Description:OLED显字符串 +param: u8 col 列位置 + u8 page 行位置 + u8 *str 字符串 +retval: void +Remarks: + + +*/ + + +void OLED_displaystr(unsigned char col,unsigned char page,unsigned char *str) +{ + while(*str !='\0') + { + if(*str >= 0xA1)//显示汉字 + { + OLED_displaychina(col,page,str); + str+=3; + col+=16; + } + else//显示英文 + { + OLED_displaychar(col,page,*str); + str+=1; + col+=8; + } + + } +} + + + + + +// /***********功能描述:显示显示BMP图片128×64起始点坐标(x,y),x的范围0~127,y为页的范围0~7*****************/ +// void OLED_DrawBMP(unsigned char x0, unsigned char y0,unsigned char x1, unsigned char y1,unsigned char BMP[]) +// { +// unsigned int j=0; +// unsigned char x,y; + +// if(y1%8==0) y=y1/8; +// else y=y1/8+1; +// for(y=y0;ySC_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 PIN31 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_0_AS_QDM1_A); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_0_AS_QDM1_A, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_0_AS_QDM1_A, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_0_AS_QDM1_A, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_0_AS_QDM1_A, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN32 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO2_1_AS_QDM1_B); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO2_1_AS_QDM1_B, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO2_1_AS_QDM1_B, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO2_1_AS_QDM1_B, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO2_1_AS_QDM1_B, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN33 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO5_0_AS_QDM1_INDEX); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO5_0_AS_QDM1_INDEX, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO5_0_AS_QDM1_INDEX, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO5_0_AS_QDM1_INDEX, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO5_0_AS_QDM1_INDEX, 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 */ + + + /* Config PIN15 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_5_AS_I2C0_SCL); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_5_AS_I2C0_SCL, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_5_AS_I2C0_SCL, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_5_AS_I2C0_SCL, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_5_AS_I2C0_SCL, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN16 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO4_3_AS_I2C0_SDA); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO4_3_AS_I2C0_SDA, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO4_3_AS_I2C0_SDA, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO4_3_AS_I2C0_SDA, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO4_3_AS_I2C0_SDA, 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(); + QDM1_Init(); + GPIO_Init(); + I2C0_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/yibaina_3061M/pmsm_pos_qdm_foc/user/main.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..b77983aa9a5ddcdb6d7a9e77327c1b7826e0cb44 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/main.c @@ -0,0 +1,81 @@ +/** + * @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 区域同理) */ +/* 建议用户放置头文件 */ + +#include "debug.h" +/* USER CODE END 0 */ +QDM_Handle g_qdm1; +ACMP_Handle g_acmp0; +PGA_Handle g_pga0; +PGA_Handle g_pga1; +TIMER_Handle g_timer0; +TIMER_Handle g_timer1; +TIMER_Handle g_timer2; +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; +I2C_Handle g_i2c0; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ + + +/* USER CODE END 1 */ + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + /* USER CODE END 2 */ + MotorMainProcess(); + + // SystemInit(); /* 系统初始化 */ + /* USER CODE BEGIN 3 */ + /* 建议用户放置初始配置代码 */ + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + /* 建议用户放置周期性执行代码 */ + + BASE_FUNC_DELAY_MS(100); + /* 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 diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_carrier.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_carrier.h new file mode 100644 index 0000000000000000000000000000000000000000..e09442d2809c0c57b91e9e53d3e19b8867e6778b --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_carrier.h @@ -0,0 +1,153 @@ +/** + * @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_pos_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" +#include "mcs_inc_enc.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); +typedef void (*MCS_GetEncAngSpd)(float *speed, float *angle); + +/** + * @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 */ + short motorSpinPos; /**< IF启动模式下电机旋转位置*/ + 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 */ + EncoderHandle *encHandle; /**< Encoder parameter 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 */ + POSCTRL_Handle posCtrl; /**< Position controller 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. */ + + MCS_GetEncAngSpd getEncAngSpd; /**< Get the angle and speed of the encoder. */ + short encReady; + float encSpeed; + float encAxisAngle; +} MTRCTRL_Handle; + +void MCS_CarrierProcess(MTRCTRL_Handle *mtrCtrl); + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_chip_config.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_chip_config.h new file mode 100644 index 0000000000000000000000000000000000000000..2fc50e46f57c28a0828d82b6cae64ab93bc3553d --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_chip_config.h @@ -0,0 +1,81 @@ +/** + * @ 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 + + #define QDMNUM QDM1 + #define QDMIRQNUM IRQ_QDM1 + #define QDMBASEADDR QDM1_BASE + +#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 + + #define QDMNUM QDM0 + #define QDMIRQNUM IRQ_QDM0 + #define QDMBASEADDR QDM0_BASE + +#endif + + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ctlmode_config.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ctlmode_config.h new file mode 100644 index 0000000000000000000000000000000000000000..0c15802674449cd26ded357c70d1f8c92284b9d7 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ctlmode_config.h @@ -0,0 +1,75 @@ +/** + * @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_ENC, + FOC_OBSERVERTYPE_SMO4TH_PLL, + FOC_OBSERVERTYPE_LUNBORG, + FOC_OBSERVERTYPE_FLUX, + FOC_OBSERVERTYPE_SMO4TH +} MOTOR_OBSERVERTYPE_CONFIG; + +typedef enum { + FOC_CONTROLMODE_SPEED = 0, + FOC_CONTROLMODE_TORQUE, + FOC_CONTROLMODE_POS +} 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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ex_common.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ex_common.h new file mode 100644 index 0000000000000000000000000000000000000000..fe7117d925d47430b82230181437b3820de1b0cb --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_ex_common.h @@ -0,0 +1,78 @@ +/** + * @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_ex_common.h + * @author MCU Algorithm Team + * @brief + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef MCU_MAGICTAG_MCS_EX_COMMON_H +#define MCU_MAGICTAG_MCS_EX_COMMON_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "interrupt_ip.h" +#include "typedefs.h" + +#define CRG_ENABLE_VALUE 3 + +#define CPU_FRQ_HZ 200000000u /* CPU frequency */ +#define CPU_MHZ 1000000u +#define TIMER_FRQ_DIV 2 + +/** + * @defgroup EXTEND EXTEND + * @brief Extend common module. + * @{ + */ + +/** + * @defgroup EXTEND_Common EXTEND Common + * @brief EXTEND common external module. + * @{ + */ + +/* Typedef definitions ------------------------------------------------------------------------- */ + +/** + * @defgroup EXTEND_Param_Def EXTEND Parameters Definition + * @brief Definition of EXTEND parameters. + * @{ + */ + +typedef struct { + IRQ_ID irqNum; /* Interrupt Number */ + void *baseAddr; /* Peripherals baseAddr */ +} NvicHandle; + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_inc_enc.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_inc_enc.h new file mode 100644 index 0000000000000000000000000000000000000000..97fbda72a0328e115b924fb85e46f9b59b92ec3a --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_inc_enc.h @@ -0,0 +1,126 @@ +/** + * @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_incremental_enc.h + * @author MCU Algorithm Team + * @brief This file provides function of QDM module and encoder speed angle calculation. + */ + +/* Define to prevent recursive inclusion ------------------------------------------------------- */ +#ifndef MCU_MAGICTAG_MCS_INC_ENC_H +#define MCU_MAGICTAG_MCS_INC_ENC_H + +/* Includes ------------------------------------------------------------------------------------ */ +#include "qdm_ip.h" +#include "mcs_ex_common.h" + +/* Macro definitions --------------------------------------------------------------------------- */ +#define SPDBUF_MAXSIZE 20 + +/** + * @brief QDM Peripheral management. + */ +typedef struct { + void *qdmAddr; /* QDM peripheral address */ + NvicHandle zPulsesNvic; +} MCS_QdmHandle; + +/** + * @brief QDM initialization structure. + */ +typedef struct { + void *qdmAddr; /**< QDM peripheral address */ + NvicHandle *zPlusesNvic; /**< z Pulse Interrupt Configuration */ + unsigned int zPlusesIrqPrio; /**< Interrupt priority */ + IRQ_PROC_FUNC zPlusesIrqFunc; /**< Interrupt function */ +} MCS_QdmInitStru; + +/** + * @brief Encoder motor parameter structure. + */ +typedef struct { + signed int mtrPPMR; /**< pulse per mechanical round */ + unsigned int zShift; /**< pulse Z shift */ + unsigned int mtrNp; /**< numbers of pole pairs */ + float ctrlPeriod; /**< The encoder calculates the control period. */ + /**< the times of compute the angle, if reach the specified num, it will be reset to 0 again */ + unsigned int timeNum; +} MCS_EncInitStru; + +/** + * @brief encoder control data structure. + */ +typedef struct { + signed int pulsePerMechRound; /**< pulses of each mechanical round */ + signed int pulsePerElecRound; /**< pulses of each eletricity period */ + signed short zShift; /**< Z-pulse cheap compensation */ + float elecAngle; /**< electricity angle */ + float mechAngle; /**< motor mechine angle */ + unsigned short cntNow; /**< counter for now */ + unsigned short cntPre; /**< counter of last record */ + signed short pulsePos; /**< Number of pulses corresponding to mechanical + position [-32768, 32767] */ + float elecSpeed; /**< elec speed, in HZ */ + signed short speedBuf[SPDBUF_MAXSIZE]; /**< speed buffer */ + signed short speedBufSize; /**< speed buffer size */ + signed short speedBufIndex; /**< speed bufer index */ + float pulseToHzPu; /**< pulse to HZ transition value */ + + unsigned short timeCnt; /**< times of compute the angle, the carrier ISR call times */ + /**< the times of compute the angle, if reach the specified num, it will be reset to 0 again */ + unsigned short timeNum; + + unsigned short pulZCnt; /**< counter of Z pulse */ + unsigned short pulseAngle; /**< Number of pulses corresponding to electrical angle. + [0, pulsePerElecRound-1] */ + float pulseToElecAngle; /**< pulse to electricity angle transition */ + unsigned short testAngle; +} EncoderHandle; +/** + * @} + */ + +/** + * @defgroup MCS_INC_ENC_Declaration incremental encoder. + * @{ + */ +void MCS_QdmInit(MCS_QdmInitStru *qdmInit); +void MCS_GetEncoderCnt(EncoderHandle *handle, QDM_RegStruct *qdm); +void MCS_GetElecAngleByEnc(EncoderHandle *handle); +void MCS_GetElecSpeedByEnc(EncoderHandle *handle); +void MCS_EncoderClear(EncoderHandle *handle); +void MCS_EncoderInit(EncoderHandle *handle, MCS_EncInitStru *encParam); +/** + * @brief Get the QDM position counter. + * @retval unsigned short QDM SCNT. + */ +static inline unsigned short MCS_GetQdmPosCnt(QDM_RegStruct *qdm) +{ + return (unsigned short)(qdm->QPOSCNT); +} +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* McuMagicTag_MCS_INC_ENC_H */ \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_motor_process.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_motor_process.h new file mode 100644 index 0000000000000000000000000000000000000000..783bf21402d5d3f5d4bdc8dc5bd9ee425d0fbf21 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_status.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_status.h new file mode 100644 index 0000000000000000000000000000000000000000..19510c78b2d63a46ca51495d8ad028e351574d1d --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_user_config.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..95a8aa17cd687e61a070c022979c3e6210a53e70 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/inc/mcs_user_config.h @@ -0,0 +1,143 @@ +/** + * @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 SYSTICK_PERIOD_US 500u /* Systick定时器的周期,单位为微秒 */ + +#define INV_CAP_CHARGE_MS 3u /* 反向电容充电时间,单位为毫秒 */ + +#define INV_VOLTAGE_BUS 24.0f // 总线电压,单位为伏特 + +#define CTRL_CURR_PERIOD 0.0001f /* 载波中断服务例程的周期,100微秒 */ +#define CTRL_SYSTICK_PERIOD 0.0005f /* Systick控制周期,500微秒 */ + +/* 采样窗口的占空比,实际时间为0.06*50us = 3us。 */ +#define SAMPLE_WINDOW_DUTY 0.06f + +/* 采样点移位作为翻转点的占空比,实际时间为0.008*50us = 0.4us。 */ +#define SAMPLE_POINT_SHIFT 0.008f + +/* 采样电阻200毫欧姆,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 /* APT同步输入源 */ + +#define APT_U APT0_BASE /* U相APT模块的基地址 */ +#define APT_V APT1_BASE /* V相APT模块的基地址 */ +#define APT_W APT2_BASE /* W相APT模块的基地址 */ + +/* User_Commond */ +#define CTRL_IF_CURR_AMP_A 1.0f /* IF控制电流幅值 */ +#define USER_TARGET_SPD_HZ 40.0f /* 用户目标速度,单位为赫兹,括号用于输入负指令 */ + +#define USER_MIN_SPD_HZ 5.0f /* 电机最小速度限制,单位为赫兹 */ +#define USER_MAX_SPD_HZ 200.0f /* 电机最大速度限制,单位为赫兹 */ +#define USER_SPD_SLOPE 30.0f /* 速度变化斜率 */ +#define USER_CURR_SLOPE (CTRL_IF_CURR_AMP_A * 5.0f) /* 电流变化斜率 */ + +/* PID PARAMS */ +#define CURRQAXIS_KP 0.7414f /* Q轴电流PID控制器的比例系数 */ +#define CURRQAXIS_KI 1256.0f /* Q轴电流PID控制器的积分系数 */ +#define CURRDAXIS_KP 0.7414f /* D轴电流PID控制器的比例系数 */ +#define CURRDAXIS_KI 1256.0f /* D轴电流PID控制器的积分系数 */ +#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.01f /* 速度PID控制器的比例系数 */ +#define SPD_KI 0.1f /* 速度PID控制器的积分系数 */ +#define SPD_LOWERLIM -1.0f /* 速度下限 */ +#define SPD_UPPERLIM 1.0f /* 速度上限 */ + +#define POS_KP 5.0f /* 位置PID控制器的比例系数 */ +#define POS_KI 0.3f /* 位置PID控制器的积分系数 */ +#define POS_KD 0.01f /* 位置PID控制器的微分系数 */ +#define POS_NS 10.0f /* 位置环Ns参数 */ +#define POS_LOWERLIM -200.0f /* 位置下限 */ +#define POS_UPPERLIM 200.0f /* 位置上限 */ + +/* 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 */ + +/* 电机参数 */ +/* Np, Rs, Ld, Lq, Psif, J, Nmax, Currmax, PPMR, zShift */ +/* mtrPsif & mtrJ 参数在这个项目中没有使用,暂时设置为0 */ +// 电机的极对数 +/* 电机的电阻,单位为欧姆 */ +/* 电机的直轴电感,单位为亨利 */ +/* 电机的交轴电感,单位为亨利 */ +/* 电机的磁链,本项目未使用 */ +/* 电机的转动惯量,本项目未使用 */ +/* 电机的最大电气转速,单位为赫兹 */ +/* 电机的最大电流,单位为安培 */ +/* 电机的每转脉冲数 */ +/* 电机的零位偏移 */ + +#define MOTORPARAM_DEFAULTS { \ + .mtrNp = 4, \ + .mtrRs = 0.5f, \ + .mtrLd = 0.000295f, \ + .mtrLq = 0.000295f, \ + .mtrPsif = 0.0f, \ + .mtrJ = 0.0f, \ + .maxElecSpd = 200.0f, \ + .maxCurr = 1.5f, \ + .mtrPPMR = 4000, \ + .zShift = 410, \ +} + +// // //1025电机 +// #define MOTORPARAM_DEFAULTS { \ +// .mtrNp = 21, \ +// .mtrRs = 2.5f, \ +// .mtrLd = 0.066f, \ +// .mtrLq = 0.066f, \ +// .mtrPsif = 0.0f, \ +// .mtrJ = 0.0f, \ +// .maxElecSpd = 200.0f, \ +// .maxCurr = 1.5f, \ +// .mtrPPMR = 4000, \ +// .zShift = 410, \ +// } + + +// // GIM4310-10 +// #define MOTORPARAM_DEFAULTS { \ +// .mtrNp = 14, \ +// .mtrRs = 1.046f, \ +// .mtrLd = 0.000344f, \ +// .mtrLq = 0.000344f, \ +// .mtrPsif = 0.0f, \ +// .mtrJ = 0.0f, \ +// .maxElecSpd = 200.0f, \ +// .maxCurr = 1.5f, \ +// .mtrPPMR = 4000, \ +// .zShift = 410, \ +// } + +#define ADC_UDC_COFFI 0.01289f /* 0.01289 = 3.3/4096*192/12 */ +// ADC和UDC的系数,用于将ADC值转换为实际电压值 +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_cmm.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_cmm.c new file mode 100644 index 0000000000000000000000000000000000000000..99766bdf9b3d4f161b1902708696cb0e75a4fc9c --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_cmm.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_cmm.h new file mode 100644 index 0000000000000000000000000000000000000000..65e5632ff7e07c1a941a257d48abc62c2f02fdd1 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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; /**<表示相电流超过保护值*/ + unsigned short overVoltErr : 1; /**<表示直流链路电压超过保护值*/ + unsigned short lowerVoltErr : 1; /**<表示直流链路电压低于保护值*/ + unsigned short overIpmTempErr : 1; /**<表示IPM温度超过保护值*/ + unsigned short revRotErr : 1; /**<表示电机为负方向*/ + unsigned short motorStalling : 1; /**<表示转子失速*/ + unsigned short overMotorTempErr : 1; /**<表示三相电流不平衡*/ + unsigned short posSnsrCommsErr : 1; /**<表示位置传感器与MCU的通信中断*/ + unsigned short posSnsrFuncErr : 1; /**<表示位置传感器报告功能错误*/ + unsigned short posSnsrCalibrErr : 1; /**<表示位置传感器无法自行校准*/ + unsigned short currOutOfBalance : 1; /**<表示转子反向旋转*/ + unsigned short phsOpenErr : 1; /**<表示相绕组断开*/ + unsigned short phsU : 1; /**<表示发生phsOpenErr时u阶段失败*/ + unsigned short phsV : 1; /**<表示发生phsOpenErr时v阶段失败*/ + unsigned short phsW : 1; /**<表示发生phsOpenErr时w阶段失败*/ + unsigned short multiPhs : 1; /**<表示发生phsOpenErr时多阶段失败*/ + } Bit; +} MotorErrStatusReg; + +/**<保护状态位定义*/ +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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user.c new file mode 100644 index 0000000000000000000000000000000000000000..e97876b7c6ec522fa82c30cbe503e2ab8de288db --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user.h new file mode 100644 index 0000000000000000000000000000000000000000..365110e10c6cd8bd5207af61f0a87b6df226fa91 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user_config.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..988c519d57dec1a68b5cd028e1e706266995e888 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/common/mcs_prot_user_config.h @@ -0,0 +1,130 @@ +/** + * @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 */ +/**<连续运行时电机或IPM的峰值相电流(A)*/ +#define PROT_MOTOR_RATED_CURR (1.0f) +/**<只有几次连续的故障检测才能触发错误状态*/ +#define PROT_CNT_LIMIT (100) +/**<只有几个连续的无故障检测才能触发错误状态的消除*/ +#define RECY_CNT_LIMIT (10000) +/**<只有几个连续的无故障检测才能触发错误状态的消除*/ +#define OVER_VOLT_RECY_CNT_LIMIT (100) +/**<只有几个连续的无故障检测才能触发错误状态的消除*/ +#define LOWER_VOLT_RECY_CNT_LIMIT (100) + +/**<过电流保护*/ +/**<处于1级时的过电流触发值(A)*/ +#define PROT_OVER_CURR_POW_DN1 (2.0f * PROT_MOTOR_RATED_CURR) +/**<处于2级时的过电流触发值(A)*/ +#define PROT_OVER_CURR_POW_DN2 (2.0f * PROT_MOTOR_RATED_CURR) +/**<处于3级时的过电流触发值(A)*/ +#define PROT_OVER_CURR_POW_DN3 (2.0f * PROT_MOTOR_RATED_CURR) +/**<处于4级时的过电流触发值(A)*/ +#define PROT_OVER_CURR_POW_OFF (2.0f * PROT_MOTOR_RATED_CURR) +#define PROT_OVER_CURR_RECY_DELTA (0.0035f) /*<从保护状态恢复时的电流间隙(A)*/ +#define PROT_OVER_CURR_LIMIT1_TIME_SEC (30.0f) /**<20%过载的最长持续时间:30秒*/ +#define PROT_OVER_CURR_LIMIT2_TIME_SEC (10.0f) /**<20%过载的最长持续时间:10秒*/ +#define PROT_OVER_CURR_LIMIT3_TIME_SEC (2.0f) /**<20%过载的最长持续时间:2秒*/ + +/**< Over voltage protection */ +#define PROT_OVER_VOLT_BRK_ON1 (26.0f) /**<处于1级时,直流链路电压触发值(V)过高*/ +#define PROT_OVER_VOLT_BRK_ON2 (27.0f) /**< Over dc-link voltage trigger value (V) when in level 2. */ +#define PROT_OVER_VOLT_BRK_ON3 (28.0f) /**< Over dc-link voltage trigger value (V) when in level 3. */ +#define PROT_OVER_VOLT_BRK_ALL (30.0f) /**< Over dc-link voltage trigger value (V) when in level 4. */ +#define PROT_OVER_VOLT_RECY_DELTA (0.5f) /**<从保护状态恢复时的电压间隙(V)*/ +#define PROT_OVER_VOLT_LIMIT1_TIME_SEC (5.0f) /**1;单循环模式:<0.5*/ +#define POS_SNSR_IPD_INJ_PERIOD (4) + +#endif \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_curr_prot.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_curr_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..da4e56f89a51d39053fad4511bb799c91070df65 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_curr_prot.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_curr_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..e9916fe491699bff3373bbc68b175b6db16d7cd7 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_dc_volt_prot.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_dc_volt_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..b0541a2e2e37ba98e8b92e6334ab2cc940b72b6c --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_dc_volt_prot.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_dc_volt_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..0435156a0add386ec4b783f4d003f4178baa2ecf --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_motor_stalling.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_motor_stalling.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee4d2d240e66f7cfb0528b2d42d4c32ada0078 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_motor_stalling.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_motor_stalling.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d1e4bed11bec0d6d73aee54de36c365588898e --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_temp_prot.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_temp_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..184ba4a3ac712690e4f808f1464a65c74a387b52 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_temp_prot.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/protection/mcs_temp_prot.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9d99a76c19f53a78ccc1257287eccfd1fc972c --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/readme.md b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..592524f05d71519a9f2ddcb106b006fe7d8b381b --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/readme.md @@ -0,0 +1,12 @@ +# pmsm_encode_qdm_2shunt_foc + +**【功能描述】** ++ 基于ECMCU105H/ECBMCU201MPC单板的单电机双电阻采样的有感Foc应用 + +**【环境要求】** ++ 所有单板电源改制为演示用的24V低压,电机选用42JSF630AS-1000 ++ 电机ABZ编码器线序分别对应功率板上ABZ通道接口 ++ 电机(绿蓝黄)相线分别对应功率板上U/V/W通道接口 + +**【IDE配置方法】** ++ chipConfig中的Sample栏目里面选中pmsm encode qdm 2shunt foc示例,然后点击生成代码即可 diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_carrier.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_carrier.c new file mode 100644 index 0000000000000000000000000000000000000000..4f8c9d377c367c0356dd195ac46543445a0d7957 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_carrier.c @@ -0,0 +1,136 @@ +/** + * @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 同步旋转坐标系角度。 + * @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: + /* 当前斜坡角度为0。 */ + if (mtrCtrl->startup.stage == STARTUP_STAGE_CURR) { + mtrCtrl->axisAngle = 0; + } else if (mtrCtrl->startup.stage == STARTUP_STAGE_SPD) { /* 中频控制相位角自加。 */ + mtrCtrl->axisAngle = IF_CurrAngleCalc(&mtrCtrl->ifCtrl, mtrCtrl->spdRefHz); + } + break; + + case FSM_RUN: + mtrCtrl->axisAngle = mtrCtrl->encAxisAngle; + break; + + default: + mtrCtrl->axisAngle = 0; + break; + } +} + +/** + * @brief 单电阻器和双电阻器的PWM波形设置和采样点设置。 + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void MCS_PwmAdcSet(MTRCTRL_Handle *mtrCtrl) +{ + MCS_ASSERT_PARAM(mtrCtrl != NULL); + SampleMode sampleMode = mtrCtrl->sampleMode; + /* 根据采样模式设置占空比. */ + if (sampleMode == DUAL_RESISTORS) { + //三相上开关PWM波的占空比为在两相静止坐标系(albe)中计算。 + 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); + /* ADC采样点位置需要根据单个电阻器的相移进行设置。*/ + mtrCtrl->setADCTriggerTimeCb(mtrCtrl->r1Sv.samplePoint[0] * mtrCtrl->aptMaxcntCmp, \ + mtrCtrl->r1Sv.samplePoint[1] * mtrCtrl->aptMaxcntCmp); + } +} + +/** + * @brief 载波中断功能。 + * @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; + /* 采样模式验证 */ + if (sampleMode > SINGLE_RESISTOR || mtrCtrl->setADCTriggerTimeCb == NULL) { + return; + } + /* 参数验证 */ + if (mtrCtrl->setPwmDutyCb == NULL || mtrCtrl->readCurrUvwCb == NULL) { + return; + } + /* 读取三相电流值。 */ + mtrCtrl->readCurrUvwCb(currUvw); + mtrCtrl->getEncAngSpd(&mtrCtrl->encSpeed, &mtrCtrl->encAxisAngle);//读取反馈速度与角度 + /* 同步角度 */ + MCS_SyncCoorAngle(mtrCtrl); + + /* 克拉克变化 UVW->A、B */ + ClarkeCalc(currUvw, currAlbe); + /* 帕克变化 A、B +角度->q、d */ + ParkCalc(currAlbe, mtrCtrl->axisAngle, &mtrCtrl->idqFbk); + + /* 状态机 */ + switch (mtrCtrl->stateMachine) { + case FSM_STARTUP: + case FSM_RUN: + CURRCTRL_Exec(&mtrCtrl->currCtrl, &mtrCtrl->vdqRef, mtrCtrl->smo.spdEst, 0); + //帕克逆变化 ,将d,q轴电流+角度逆变换为α,β。 + InvParkCalc(&mtrCtrl->vdqRef, mtrCtrl->axisAngle, vab); + //单电阻器和双电阻器的PWM波形设置和采样点设置。 + MCS_PwmAdcSet(mtrCtrl); + break; + + case FSM_CAP_CHARGE: + case FSM_CLEAR: + case FSM_IDLE: + break; + + default: + vab->alpha = 0.0f; + vab->beta = 0.0f; + MCS_PwmAdcSet(mtrCtrl); + break; + } +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_inc_enc.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_inc_enc.c new file mode 100644 index 0000000000000000000000000000000000000000..9769c9b5011aa1cd2969e790585278c635b93e51 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_inc_enc.c @@ -0,0 +1,236 @@ +/** + * @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_incremental_enc.c + * @author MCU Algorithm Team + * @brief This file provides function of QDM module and encoder speed angle calculation. + */ +#include "mcs_inc_enc.h" +#include "crg.h" +#include "debug.h" +#include "mcs_math_const.h" + +#define FILTER_TIME_A 100 /* Unit: clock cycles */ +#define FILTER_TIME_B 100 /* Unit: clock cycles */ +#define FILTER_TIME_Z 100 /* Unit: clock cycles */ +#define ENC_SPEED_BUF_SIZE 10 +#define ENC_HALF_PPR 5000u +#define ENC_MAX_POS 65536u +/** + * @brief QMD Initialization. + * @param qdmInit MCS_QdmInitStru. + * @retval None. + */ +void MCS_QdmInit(MCS_QdmInitStru *qdmInit) +{ + QDM_RegStruct *qdm = qdmInit->qdmAddr; + + HAL_CRG_IpEnableSet(qdmInit->qdmAddr, CRG_ENABLE_VALUE); + + /* Internal counters are not affected by emulator pause CPU */ + qdm->QEMUMODE.BIT.emu_mode = QDM_EMULATION_MODE_RUN_FREE; + + /* Quadrature input decoding mode. Inputs are quadrature encoder A, B, Z phase signals. */ + qdm->QCTRL.BIT.qdu_mode = QDM_QUADRATURE_COUNT; + +/** + * This parameter is valid only when the quadrature count mode is + * used. In other modes, the frequency is multiplied by 2x. + */ + qdm->QCTRL.BIT.qdu_xclk = QDM_4X_RESOLUTION; + + /* xCLK-xDIRCount mode. */ + qdm->QPPUCTRL.BIT.pcnt_mode = QDM_PPU_COUNT_MODE_CLK_DIR; + + /* QDM position counter reset select: overflow reset (upflow, underflow) */ + qdm->QPPUCTRL.BIT.pcnt_rst_mode = QDM_POSITION_RESET_MAX_POS; + + /* QDM initialization position counter mode: disabled */ + qdm->QPPUCTRL.BIT.pcnt_idx_init_mode = QDM_POSITION_INIT_DO_NOTHING; + + /* QDM Index latch mode select: latch at the rising edge of index */ + qdm->QPPUCTRL.BIT.pcnt_idx_lock_mode = QDM_LOCK_RISING_INDEX; + + qdm->QPOSMAX = 0xFFFF; /* QDM Position Count Max */ + + /* ABZ filtering time */ + qdm->QDMAFT.BIT.qdma_ft_level = FILTER_TIME_A; + qdm->QDMBFT.BIT.qdmb_ft_level = FILTER_TIME_B; + qdm->QDMIFT.BIT.qdmi_ft_level = FILTER_TIME_Z; + +/** + * QDM Position count value. When ppu_en is disabled or counting stops after the emulator is + * connected, software can write QPOSCNT. + */ + qdm->QPOSCNT = 0; + + /* QDM Position processing unit PPU enable 1: PPU position counter starts counting */ + qdm->QCTRL.BIT.ppu_en = BASE_CFG_ENABLE; + + /* Enable z-pulse interrupt */ + if (qdmInit->zPlusesIrqFunc != NULL && qdmInit->zPlusesNvic->baseAddr != NULL) { + IRQ_SetPriority(qdmInit->zPlusesNvic->irqNum, qdmInit->zPlusesIrqPrio); + IRQ_Register(qdmInit->zPlusesNvic->irqNum, qdmInit->zPlusesIrqFunc, qdmInit->zPlusesNvic); + DCL_QDM_EnableInterrupt(qdm, QDM_INT_INDEX_EVNT_LATCH); + IRQ_EnableN(qdmInit->zPlusesNvic->irqNum); + } +} + +/** + * @brief Get the Encoder Cnt object. + * @param enc encoder handle. + * @param qdm QDM_RegStruct. + * @retval None. + */ +void MCS_GetEncoderCnt(EncoderHandle *enc, QDM_RegStruct *qdm) +{ + signed short tmpS16; + + enc->cntNow = qdm->QPOSCNT; + /* Get pulse conut in unit period */ + tmpS16 = (signed short)(enc->cntNow - enc->cntPre); + + enc->pulsePos += tmpS16; /* Total number of pulses since power-on. */ + enc->pulseAngle = (unsigned short)qdm->QPOSCNT; + + enc->cntPre = enc->cntNow; +} + +/** + * @brief Get the Elec Angle By Enc object. + * @param enc Encoder handle. + * @retval signed short elecAngle Angle in electronic, S16degree. + */ +void MCS_GetElecAngleByEnc(EncoderHandle *enc) +{ + signed int tmpS32; + + tmpS32 = enc->pulseAngle - enc->pulZCnt; + /* Align electric angle & enc angle */ + tmpS32 += enc->zShift; + /* Limit max value */ + if (tmpS32 > INT16_MAX) { + tmpS32 -= ENC_MAX_POS; + } + /* Limit min value */ + if (tmpS32 < -INT16_MAX) { + tmpS32 += ENC_MAX_POS; + } + while (tmpS32 >= enc->pulsePerElecRound) { + tmpS32 -= enc->pulsePerElecRound; + } + while (tmpS32 < 0) { + tmpS32 += enc->pulsePerElecRound; + } + float tempElecAngle = (signed short)(tmpS32 * enc->pulseToElecAngle); + /* Convert short to float angle type */ + enc->elecAngle = tempElecAngle * DIGITAL_TO_RAD; +} + +/** + * @brief Get the Elec Speed By Enc object. + * @param enc Encoder handle. + * @retval None. + */ +void MCS_GetElecSpeedByEnc(EncoderHandle *enc) +{ + signed int tmpS32; + signed short halfPPR = ENC_HALF_PPR; + unsigned short index = enc->speedBufIndex; + + enc->timeCnt++; + if (enc->timeCnt >= enc->timeNum) { + enc->timeCnt = 0; + } else { + return; + } + + /* Get pulse conut in unit period */ + tmpS32 = enc->pulsePos - enc->speedBuf[index]; + /* Limit max value */ + if (tmpS32 > halfPPR) { + tmpS32 -= ENC_MAX_POS; + } + /* Limit min value */ + if (tmpS32 < -halfPPR) { + tmpS32 += ENC_MAX_POS; + } + /* Convert unit pulse count to Hz */ + enc->elecSpeed = tmpS32 * enc->pulseToHzPu; + enc->speedBuf[index] = enc->pulsePos; + index++; + /* Store current speed for calcule the average */ + if (index >= enc->speedBufSize) { + enc->speedBufIndex = 0; + } else { + enc->speedBufIndex = index; + } +} + +/** + * @brief Clear the historical cache and time count. + * @param enc Encoder handle. + * @retval None. + */ +void MCS_EncoderClear(EncoderHandle *enc) +{ + enc->speedBufIndex = 0; + for (unsigned short i = 0; i < enc->speedBufSize; i++) { + enc->speedBuf[i] = enc->pulsePos; + } + + enc->timeCnt = 0; +} + +/** + * @brief Initialzer of encoder struct handle. + * @param enc Encoder handle. + * @param encParam Encoder and Motor parameter. + * @retval None. + */ +void MCS_EncoderInit(EncoderHandle *enc, MCS_EncInitStru *encParam) +{ + if (encParam->mtrPPMR == 0 || encParam->mtrNp == 0) { + return; + } + + enc->pulsePerMechRound = encParam->mtrPPMR; + enc->pulsePerElecRound = encParam->mtrPPMR / encParam->mtrNp; + enc->zShift = encParam->zShift; + /* Clear count value */ + enc->cntNow = 0; + enc->cntPre = 0; + + enc->pulsePos = 0; + enc->pulseAngle = 0; + enc->elecAngle = 0; + /* Initial speed buffer */ + enc->speedBufSize = ENC_SPEED_BUF_SIZE; /* Max = 10 */ + enc->speedBufIndex = 0; + for (unsigned short i = 0; i < enc->speedBufSize; i++) { + enc->speedBuf[i] = enc->pulsePos; + } + /* Clear time count value */ + enc->timeCnt = 0; + enc->timeNum = encParam->timeNum; + enc->elecSpeed = 0.0f; /* Hz */ + /* Convert unit pulse count to Hz */ + enc->pulseToHzPu = (float)(1.0f / + (enc->pulsePerElecRound * enc->timeNum * enc->speedBufSize * encParam->ctrlPeriod)); + /* Convert unit pulse count to electric angle */ + enc->pulseToElecAngle = (float)(65536.0f / enc->pulsePerElecRound); +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_motor_process.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_motor_process.c new file mode 100644 index 0000000000000000000000000000000000000000..6626f9a4d4985ea8ac6eea1cc8cc1f95add8ecff --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/src/mcs_motor_process.c @@ -0,0 +1,1047 @@ +/** + * @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 42JSF630AS-1000. + * 2) Select the pmsm encode qdm 2shunt foc example in the sample column + of chipConfig and click Generate Code. + * 3) It's power supply must be changed to 24V. + */ +#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 "mcs_inc_enc.h" +#include +#include "debug.h" + + +/*------------------------------- 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 +#define IRQ_QDM0_PRIORITY 7 /* the QDM encoder IRQ priority, highest */ +#define ENC_TIMES_NUM 5 +/*------------------------------- 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}; + +extern __UINT16_TYPE__ last_raw_Angle; +/* QDM */ +typedef struct { + MCS_QdmHandle qdm; +} PeriphHandle; +static PeriphHandle g_periph = {.qdm = {.qdmAddr = QDMBASEADDR, + .zPulsesNvic = {.irqNum = QDMIRQNUM, + .baseAddr = QDMBASEADDR}}}; +/* Motor control handle */ +static MTRCTRL_Handle g_mc = {0}; +/* QDM control handle */ +static EncoderHandle g_enc = {0}; + + + + +/** + * @brief 获取编码器的角度和速度。 + * @param speed 速度指针。 + * @param angle 角度指针。 + * @retval 无。 + */ + +static void GetEncAngSpd(float* speed, float* angle) +{ + MCS_GetEncoderCnt(&g_enc, QDMNUM);// 获取编码器计数值 + // /* 计算电机电角度 -π ~ π */ + MCS_GetElecAngleByEnc(&g_enc); // 根据编码器数据计算电机电角度 + // /* 计算电机速度 */ + MCS_GetElecSpeedByEnc(&g_enc); // 根据编码器数据计算电机速度 + *speed = g_enc.elecSpeed; // 将计算得到的电机速度赋值给传入的速度指针 + *angle = g_enc.elecAngle; // 将计算得到的电机电角度赋值给传入的角度指针 + + + + +} + + +static void ISR_QdmzPulses(void* args) +{ + NvicHandle* qdmHandle = (NvicHandle*)args; // 将传入的参数转换为NvicHandle指针 + /* 清除QDM中断标志 */ + DCL_QDM_ClearInterrupt((QDM_RegStruct*)qdmHandle->baseAddr, QDM_INT_INDEX_EVNT_LATCH); // 清除QDM事件捕获中断标志 + IRQ_ClearN(qdmHandle->irqNum); // 清除中断请求 + + g_enc.pulZCnt = MCS_GetQdmPosCnt(qdmHandle->baseAddr); + g_mc.motorSpinPos++; // 增加电机旋转位置计数 + if (g_mc.encReady == 0) { + /* Z脉冲标志用于确定在初始启动期间IF预设位是否成功使用。 */ + g_mc.encReady = 1; // 如果编码器尚未准备好,设置编码器准备好标志 + } + +} + + + +/* Motor POS loop PID param. */ +static void POSCTRL_InitWrapper(POSCTRL_Handle *posHandle, float ts) +{ + /* Position loop param assignment. */ + PID_Param posPi = { + .kp = POS_KP, + .ki = POS_KI, + .kd = POS_KD, + .ns = POS_NS, + .lowerLim = POS_LOWERLIM, + .upperLim = POS_UPPERLIM, + }; + /* Position loop param init. */ + POSCTRL_Init(posHandle, &posPi, ts); +} + +/* 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); +} + +/*------------------------------- Function Definition -----------------------------------------------*/ +/** + * @brief 系统标记的初始化器。 + * @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; /* 初始化电流控制器 */ + g_mc.aptMaxcntCmp = g_apt0.waveform.timerPeriod; + g_mc.sampleMode = DUAL_RESISTORS; + g_mc.obserType = FOC_OBSERVERTYPE_ENC; /* 启动foc观察模式*/ + g_mc.controlMode = FOC_CONTROLMODE_POS; /* 启动电机控制模式 */ + g_mc.adcCurrCofe = ADC_CURR_COFFI; + g_mc.spdAdjustMode = CUST_SPEED_ADJUST; + g_mc.uartConnectFlag = DISCONNECT; + g_mc.spdCmdHz = 35.0f; /* Motor initialization speed */ + + g_mc.adc0Compensate = ADC0COMPENSATE; /* u相电流初始化adc移位微调值 */ + g_mc.adc1Compensate = ADC1COMPENSATE; /* w相电流初始化adc移位微调值*/ + + IF_Init(&g_mc.ifCtrl, CTRL_IF_CURR_AMP_A, USER_CURR_SLOPE, CTRL_SYSTICK_PERIOD, CTRL_CURR_PERIOD);//IF初始化电流 + RMG_Init(&g_mc.spdRmg, CTRL_SYSTICK_PERIOD, USER_SPD_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); + //电机速度回路PI参数。 + SPDCTRL_InitWrapper(&g_mc.spdCtrl, CTRL_SYSTICK_PERIOD); + //电机位置回路PI参数。 + POSCTRL_InitWrapper(&g_mc.posCtrl, CTRL_SYSTICK_PERIOD * 5.0f); /* Position loop control period */ + //电机电流回路PI参数。 + CURRCTRL_InitWrapper(&g_mc.currCtrl, &g_mc.idqRef, &g_mc.idqFbk, CTRL_CURR_PERIOD); + + MotorProt_Init(&g_mc.prot); /* 初始化保护状态通用 */ + 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.0f; + mtrCtrl->spdRefHz = 0.0f; + mtrCtrl->motorSpinPos = 0; + /* 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); + STARTUP_Clear(&mtrCtrl->startup); + R1SVPWM_Clear(&mtrCtrl->r1Sv); + POSCTRL_Clear(&mtrCtrl->posCtrl); + MCS_EncoderClear(&g_enc); + + 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. + * @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. + * @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 构造一个新的mcs启动开关对象。 + * @param mtrCtrl The motor control handle. + * @retval None. + */ +static void MCS_StartupSwitch(MTRCTRL_Handle *mtrCtrl) +{ + // 确保传递的电机控制句柄不是NULL + MCS_ASSERT_PARAM(mtrCtrl != NULL); + // 获取启动阶段处理结构体的指针 + STARTUP_Handle *startup = &mtrCtrl->startup; + // 获取dq轴参考值结构体的指针 + DqAxis *idqRef = &mtrCtrl->idqRef; + // 获取目标电流幅值 + float iftargetAmp = mtrCtrl->ifCtrl.targetAmp; + // 获取速度参考值(Hz) + float spdRefHz = mtrCtrl->spdRefHz; + // 根据当前启动阶段执行相应操作 + switch (startup->stage) { + case STARTUP_STAGE_CURR: + if (mtrCtrl->ifCtrl.curAmp >= iftargetAmp) { //IF采样电流大于IF目标电流时。 + /* 阶段转换 */ + // 设置q轴参考电流为目标电流值 + idqRef->q = iftargetAmp; + // 更改启动阶段至速度阶段 + startup->stage = STARTUP_STAGE_SPD; + mtrCtrl->encReady = 0; /* 启动阶段清除Z信号干扰错误 */ + + } else { + /* 增加电流幅值 */ + // 计算并设置新的q轴参考电流 + idqRef->q = IF_CurrAmpCalc(&mtrCtrl->ifCtrl); + // 在此阶段保持速度参考为0 + spdRefHz = 0.0f; + } + break; + + case STARTUP_STAGE_SPD: // 当前处于速度启动阶段 + /* 提高电流频率 */ + // 判断电机是否已经旋转了足够圈数 + if (mtrCtrl->motorSpinPos > 3) { /* 3是If模式下的电机转数 */ + /* 阶段转换 */ + // 转换状态机至运行状态 + mtrCtrl->stateMachine = FSM_RUN; + } else { + /* 速度斜坡生成 */ + // 执行速度斜坡生成函数,并设定一个固定的拖动速度 + spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, 5.0f); /*5.0f为If模式力拖动速度*/ + } + 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; + /* 为自举电容器充电做准备。 */ + AptTurnOnLowSidePwm(aptAddr, mtrCtrl->aptMaxcntCmp); + /* Out put pwm */ + MotorPwmOutputEnable(aptAddr); + } +} + +/***************************************** + * @brief 系统计时器勾选任务。 + * @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++; + /* 电机状态的预处理。 */ + MotorStatePerProc(statusReg, stateMachine); + /* statemachine */ + switch (*stateMachine) { + case FSM_IDLE: + /*在电机启动前设置smo估计速度*/ + CheckSysCmdStart(mtrCtrl, aptAddr, statusReg, stateMachine); + break; + case FSM_CAP_CHARGE: + /* Bootstrap电容充电定时 */ + CheckBootstrpCapChargeTime(mtrCtrl, stateMachine); + break; + /* 启动前清除参数 */ + case FSM_CLEAR: + ClearBeforeStartup(mtrCtrl); + *stateMachine = FSM_STARTUP; + break; + case FSM_STARTUP: + // 构造一个新的mcs启动开关对象。 + MCS_StartupSwitch(mtrCtrl); + break; + case FSM_RUN: + if (mtrCtrl->controlMode == FOC_CONTROLMODE_SPEED) { /* Speed control mode */ + /* 速度斜坡控制 */ + mtrCtrl->spdRefHz = RMG_Exec(&mtrCtrl->spdRmg, mtrCtrl->spdCmdHz); + } else if (mtrCtrl->controlMode == FOC_CONTROLMODE_POS) { /* Position control mode */ + mtrCtrl->sysTickCnt++; + POSCTRL_SetSlope(&mtrCtrl->posCtrl, mtrCtrl->spdCmdHz);//设置位置斜坡 + /* 200.0是目标位置,用户可以重新定义 */ + // POSCTRL_SetTarget(&mtrCtrl->posCtrl, 0.5 *DOUBLE_PI * g_motorParam.mtrNp);//定位环目标位置设置。 + + float posFbk = POSCTRL_AngleExpand(&mtrCtrl->posCtrl, mtrCtrl->axisAngle); + + if (mtrCtrl->sysTickCnt % 5 == 0) { /* 5是位置环划分系数。*/ + mtrCtrl->spdRefHz = POSCTRL_Exec(&mtrCtrl->posCtrl, mtrCtrl->posCtrl.posTarget, posFbk); + } + } + /* 速度环路控制 */ + mtrCtrl->idqRef.q = SPDCTRL_Exec(&mtrCtrl->spdCtrl, mtrCtrl->spdRefHz, mtrCtrl->encSpeed);//用速度偏差值,求出所需Q轴电流 + + 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. + * @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. + * @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. + * @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. + * @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. + * @param tempResisValue Temperature sensor resistance. + * @retval None. + */ +static float TempTable(float tempResisValue) +{ + float boardTemp = 0.0f; + /* 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 执行异常反馈速度保护动作。 + * @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 Check abnormal feedback speed. + * @retval None. + */ +static void CheckSpdFbkStatus(void) +{ + static short errorSpdStatus = 0; + static short errorDeltaSpdStatus = 0; + /* Detect the nan value. */ + if (isnan(g_mc.encSpeed) || isnan(g_mc.idqRef.q)) { + errorSpdStatus++; + } else { + errorSpdStatus = 0; + } + if (g_mc.stateMachine == FSM_RUN) { + /* 检测反馈速度异常。定义10为速度误差值,0.5为当前误差值*/ + if (Abs(g_mc.spdRefHz - g_mc.encSpeed) >= CNT_10 && g_mc.idqRef.q <= 0.5f) { + errorDeltaSpdStatus++; + } + } + /*如果计数超过5000次,则执行保护动作. */ + if (errorSpdStatus >= CNT_5000 || errorDeltaSpdStatus >= CNT_5000) { + errorSpdStatus = 0; + errorDeltaSpdStatus = 0; + SpdFbkErrorProt_Exec(); + } +} +/** + * @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); + static float potentiomitorAdcValue = 0.0f; + static float spdCmdHz = 0; + static float spdCmdHzLast = 35.0f; /* 35.0 is spdCmdHzLast init value */ + HAL_ADC_SoftTrigSample(&ADCPTT_HANDLE, ADCPTTSOCNUM); + BASE_FUNC_DELAY_US(10); /* Delay 10 us. */ + potentiomitorAdcValue = (float)HAL_ADC_GetConvResult(&ADCPTT_HANDLE, ADCPTTSOCNUM); + /* 4045.0 is adc sample max value of potentiomitor, convert max spd to 200.0Hz */ + spdCmdHz = potentiomitorAdcValue / 4045.0f * USER_MAX_SPD_HZ;//电位器控制速度 + // spdCmdHz=uart_spdcmd;//串口控制速度 + + POSCTRL_SetTarget(&g_mc.posCtrl,uart_poscmd * g_motorParam.mtrNp);//串口控制位置转动 + + // POSCTRL_SetTarget(&g_mc.posCtrl,potentiomitorAdcValue / 4045.0f * 6.28 * g_motorParam.mtrNp);//电位器控制电机位置转动 + + + if (Abs(spdCmdHzLast - spdCmdHz) < 1.0f) { /* Ignore changes less than 1. */ + return; + } + spdCmdHzLast = spdCmdHz; + if (spdCmdHz < USER_MIN_SPD_HZ) { /* USER_MIN_SPD_HZ is spdCmdHz lower limit */ + spdCmdHz = USER_MIN_SPD_HZ; /* USER_MIN_SPD_HZ is spdCmdHz lower limit */ + } + if (spdCmdHz > g_mc.mtrParam.maxElecSpd) { /* spdCmdHz upper limit */ + spdCmdHz = g_mc.mtrParam.maxElecSpd; /* spdCmdHz upper limit */ + } + if (g_mc.spdAdjustMode == CUST_SPEED_ADJUST) { + g_mc.spdCmdHz = spdCmdHz; + } +} + +/** + * @brief 用于电机状态机回叫功能的系统定时器ISR。 + * @param param The systick timer handle. + * @retval None. + * + */ +void MotorStatemachineCallBack(void *param) +{ + /* Verify Parameters */ + MCS_ASSERT_PARAM(param != NULL); + BASE_FUNC_UNUSED(param); + /* 读取电源板温度和电压。*/ + ReadBoardTempAndUdc(); + /* 电机错误状态检查. */ + TSK_SystickIsr(&g_mc, g_apt); + if (g_mc.prot.motorErrStatus.all == 0) { + /* 电机错误状态检查 */ + CheckSpdFbkStatus(); + /* 电机失速检测。 */ + STP_Det_ByCurrSpd(&g_mc.prot.stall, &g_mc.prot.motorErrStatus, g_mc.encSpeed, g_mc.idqFbk); + STP_Exec(&g_mc.prot.motorErrStatus, g_apt); + } + /* 电机过电压检测。 */ + 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); + /* 电机低电压检测. */ + 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); + /* 电源板超温检测. */ + 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); + + /* 如果保护级别==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 初始化电机控制器的数据结构。 + * @retval None. + */ +static void InitSoftware(void) +{ + /* 正在初始化电机控制参数 */ + TSK_Init(); + /* Read phase-uvw current */ + g_mc.readCurrUvwCb = ReadCurrUvw; + g_mc.setPwmDutyCb = SetPwmDutyCp; + g_mc.setADCTriggerTimeCb = SetADCTriggerTime; + g_mc.encHandle = &g_enc; + + MCS_EncInitStru encMotorParam; + EncoderHandle* enc = &g_enc; + encMotorParam.mtrNp = g_motorParam.mtrNp; + encMotorParam.mtrPPMR = g_motorParam.mtrPPMR; + encMotorParam.zShift = g_motorParam.zShift; + encMotorParam.ctrlPeriod = CTRL_CURR_PERIOD; + encMotorParam.timeNum = ENC_TIMES_NUM; + MCS_EncoderInit(enc, &encMotorParam); /* encoder Initializing Parameter Configurations. */ + + /* MCU peripheral configuration function used for initial motor control. */ + g_mc.getEncAngSpd = GetEncAngSpd; /* Callback function for obtaining the encoder speed angle. */ +} + +/** + * @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 fan APT master/slave synchronization */ + 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); + } + } +} + +/** + * @brief 用户应用程序的主入口函数。 + * @retval BSP_OK 返回状态。 + */ +int MotorMainProcess(void) +{ + unsigned int tickNum1Ms = 2; /* 定义1毫秒的计时器滴答数 */ + static unsigned int tickCnt1Ms = 0; /* 静态变量,用于记录1毫秒滴答计数 */ + unsigned int tickNum500Ms = 1000; /* 定义500毫秒的计时器滴答数 */ + static unsigned int tickCnt500Ms = 0; /* 静态变量,用于记录500毫秒滴答计数 */ + + SystemInit(); /* 系统初始化 */ + HMI_Init(); /* 初始化串口中断,用于人机交互接口 */ + HAL_TIMER_Start(&g_timer0); /* 启动定时器0 */ + HAL_TIMER_Start(&g_timer1); /* 启动定时器1 */ + + + AptMasterSalveSet(); /* 设置主从设备 */ + /* 在启动前禁用PWM输出。 */ + MotorPwmOutputDisable(g_apt); /* 禁用PWM输出 */ + /* 软件初始化。 */ + InitSoftware(); /* 初始化软件相关设置 电机参数初始化*/ + + /* QDM使用算法驱动的速度和角度采集 */ + static MCS_QdmInitStru qdmInit; /* QDM初始化结构体 */ + qdmInit.qdmAddr = g_periph.qdm.qdmAddr; /* 设置QDM地址 */ + + qdmInit.zPlusesIrqFunc = ISR_QdmzPulses; /* 设置QDM零脉冲中断服务函数 */ + + qdmInit.zPlusesNvic = &g_periph.qdm.zPulsesNvic; /* 设置QDM零脉冲中断控制器 */ + qdmInit.zPlusesIrqPrio = IRQ_QDM0_PRIORITY; /* 设置QDM零脉冲中断优先级 */ + MCS_QdmInit(&qdmInit); /* 初始化QDM,必须在使能载波中断之前执行。 */ + + /* 启动PWM时钟。 */ + HAL_APT_StartModule(RUN_APT0 | RUN_APT1 | RUN_APT2); /* 启动APT模块 */ + /* 系统定时器时钟延迟。 */ + BASE_FUNC_DELAY_MS(ADC_READINIT_DELAY); /* 延迟,等待ADC初始化 */ + TrimInitAdcShiftValue(&g_mc); /* 初始化ADC移位值 */ + BASE_FUNC_DELAY_MS(MOTOR_START_DELAY); /* 延迟,等待电机启动 */ + while (1) { + + /* 循环发送数据到主机 */ + HMI_Process_Tx(&g_mc); /* 处理人机交互接口的发送数据 */ + if (g_mc.msTickCnt - tickCnt1Ms >= tickNum1Ms) { /* 检查是否达到1毫秒的计时 */ + tickCnt1Ms = g_mc.msTickCnt; /* 更新1毫秒滴答计数 */ + /* 用户代码1毫秒事件 */ + HMI_Process_Rx(&g_mc); /* 处理人机交互接口的接收数据 */ + /* 用户代码1毫秒事件 */ + } + + if (g_mc.msTickCnt - tickCnt500Ms >= tickNum500Ms) { /* 检查是否达到500毫秒的计时 */ + if (SysIsError(&g_mc.statusReg) != true) { /* 检查系统是否出现错误 */ + /* 如果系统状态正常,则切换LED灯的状态。 */ + HAL_GPIO_TogglePin(&LED1_HANDLE, LED1_PIN); /* 切换LED灯的状态 */ + } + tickCnt500Ms = g_mc.msTickCnt; /* 更新500毫秒滴答计数 */ + } + } + return 0; +} diff --git a/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/cust_process.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/cust_process.c new file mode 100644 index 0000000000000000000000000000000000000000..69f95195fc6f334ce99645a0aab967e5b7ab11c2 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/cust_process.c @@ -0,0 +1,639 @@ +/** + * @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" +#include "mcs_inc_enc.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 /* 数据段的第二个元素 */ +#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_ENC_MTRPPMR 0x01 /* Set encoder lines */ +#define SET_ENC_ZSHIFT 0x02 /* Set encoder zero point shift */ + +#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_ENC) { + ackCode = 0X03; + mtrCtrl->obserType = FOC_OBSERVERTYPE_ENC; + 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, 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, 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, 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 encoder observer parameters. + * @param encHandle The observer control handle. + * @param rxData Receive buffer + */ +static void SetObserverEncParams(EncoderHandle *encHandle, CUSTDATATYPE_DEF *rxData) +{ + /* Get command code. */ + int cmdCode = (int)(rxData->data[DATA_SEGMENT_TWO].typeF); + switch (cmdCode) { + case SET_ENC_MTRPPMR: /* Set encoder MTRPPMR. */ + encHandle->pulsePerMechRound = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X0D; + CUST_AckCode(g_uartTxBuf, ackCode, encHandle->pulsePerMechRound); + break; + case SET_ENC_ZSHIFT: /* Set encoder zero shift. */ + encHandle->zShift = rxData->data[DATA_SEGMENT_THREE].typeF; + ackCode = 0X0E; + CUST_AckCode(g_uartTxBuf, ackCode, encHandle->zShift); + break; + default: + break; + } +} + +/** + * @brief 设置观察者参数。 + * @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_ENC) { + SetObserverEncParams(mtrCtrl->encHandle, rxData); + mtrCtrl->encHandle->pulsePerElecRound = mtrCtrl->encHandle->pulsePerMechRound / mtrCtrl->mtrParam.mtrNp; + } +} + +/** + * @brief 设置电机速度和速度斜率。 + * @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 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); + /* 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->encSpeed * 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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/cust_process.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/cust_process.h new file mode 100644 index 0000000000000000000000000000000000000000..60fe69bb966d5f398468c8093e266796391de4e5 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/hmi_module.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/hmi_module.c new file mode 100644 index 0000000000000000000000000000000000000000..f6f762ad21f7ac7b422eae440a16fba74a8ba2fd --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/hmi_module.c @@ -0,0 +1,58 @@ +/** + * @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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/hmi_module.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/hmi_module.h new file mode 100644 index 0000000000000000000000000000000000000000..056f8d7310eb14335c256933e8d998bf09919cc6 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/protocol.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/protocol.c new file mode 100644 index 0000000000000000000000000000000000000000..987b4c5a591e80ddcb15271cd1ce31e277d4d5a7 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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 (int i = 0; i < num; i++) { + sum += *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 int 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++) { + int floatIndex = 0; + int 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 int 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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/protocol.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..33f0f49c252ad63e28ae291829646b7fe8c94180 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/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 { + 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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.c b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.c new file mode 100644 index 0000000000000000000000000000000000000000..8ded818032d15a7a2741d987f55649d31b493d4a --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.c @@ -0,0 +1,234 @@ +/** + * @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" +#include +/* 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 (115200) + +/* 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; +__UINT32_TYPE__ uart_spdcmd;//串口速度命令 +double uart_poscmd; //串口位置命令 + +/** + * @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 */ +} + +__UINT32_TYPE__ ascii_to_int_manual(const __UINT8_TYPE__ *buf, __UINT8_TYPE__ len) { + __UINT32_TYPE__ result = 0; + bool is_negative = false; + __UINT8_TYPE__ i = 0; + + // 检查符号位 + if (len > 0 && buf[0] == '-') { + is_negative = true; + i = 1; // 跳过符号位 + } + + // 逐字符转换 + for (; i < len; i++) { + if (buf[i] < '0' || buf[i] > '9') { + break; // 遇到非数字字符停止 + } + + // 检查溢出 + // if (result > (INT32_MAX - (buf[i] - '0')) / 10) { + // return is_negative ? INT32_MIN : INT32_MAX; + // } + + result = result * 10 + (buf[i] - '0'); + } + + return is_negative ? -result : result; +} + + + +/** + * @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; + + uart_spdcmd=ascii_to_int_manual(g_uartRxBuf, 3);//字符串转整型 + uart_poscmd=atof(g_uartRxBuf);//字符串转浮点 + 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/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.h b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.h new file mode 100644 index 0000000000000000000000000000000000000000..fce601208f2dedcea79d71cb42959744fecb5983 --- /dev/null +++ b/vendor/yibaina_3061M/pmsm_pos_qdm_foc/user/pmsm_encode_qdm_2shunt_foc/user_interface/uart_module.h @@ -0,0 +1,48 @@ +/** + * @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" + +extern __UINT32_TYPE__ uart_spdcmd; +extern double uart_poscmd; +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/yibaina_3061M/uart_it_Indefinite length/readme.md b/vendor/yibaina_3061M/uart_it_Indefinite length/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..ead38b7722f2b4643ed05ae06de3312b2b2c3a35 --- /dev/null +++ b/vendor/yibaina_3061M/uart_it_Indefinite length/readme.md @@ -0,0 +1,21 @@ +# uart_it_Indefinite length + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板板的uart中断不定长接收解决方案 + +**【环境要求】** + +- uart0与电脑上位机做通信 + + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 + + + +【操作说明】 + +打开串口助手,可以实现串口的接收发。 + diff --git a/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/feature.h b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..4b32963f50a3c72641dbb9937e56cf6e091d5f96 --- /dev/null +++ b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/feature.h @@ -0,0 +1,120 @@ +/** + * @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. + * @date 2025-05-08 11:20:52 + */ + +#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. */ + +#define MCS_PARAM_CHECK MACRO_ENABLE +#define APT_PARAM_CHECK MACRO_ENABLE +#define ADC_PARAM_CHECK MACRO_ENABLE +#define CAPM_PARAM_CHECK MACRO_ENABLE +#define CRG_PARAM_CHECK MACRO_ENABLE +#define I2C_PARAM_CHECK MACRO_ENABLE +#define UART_PARAM_CHECK MACRO_ENABLE +#define SPI_PARAM_CHECK MACRO_ENABLE +#define TIMER_PARAM_CHECK MACRO_ENABLE +#define IWDG_PARAM_CHECK MACRO_ENABLE +#define WWDG_PARAM_CHECK MACRO_ENABLE +#define GPIO_PARAM_CHECK MACRO_ENABLE +#define GPT_PARAM_CHECK MACRO_ENABLE +#define DMA_PARAM_CHECK MACRO_ENABLE +#define CRC_PARAM_CHECK MACRO_ENABLE +#define CFD_PARAM_CHECK MACRO_ENABLE +#define CMM_PARAM_CHECK MACRO_ENABLE +#define CAN_PARAM_CHECK MACRO_ENABLE +#define FLASH_PARAM_CHECK MACRO_ENABLE +#define PMC_PARAM_CHECK MACRO_ENABLE +#define ACMP_PARAM_CHECK MACRO_ENABLE +#define DAC_PARAM_CHECK MACRO_ENABLE +#define PGA_PARAM_CHECK MACRO_ENABLE +#define IOCMG_PARAM_CHECK MACRO_ENABLE +#define QDM_PARAM_CHECK MACRO_ENABLE + +/* 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/yibaina_3061M/uart_it_Indefinite length/user/generatecode/main.h b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..1746274b02f13c78e70723d5493155ea8f6f34e6 --- /dev/null +++ b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/main.h @@ -0,0 +1,60 @@ +/** + * @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. + * @date 2025-05-08 11:20:52 + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_SYSTEM_INIT_H +#define McuMagicTag_SYSTEM_INIT_H + +#include "uart.h" +#include "uart_ex.h" +#include "crg.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 + +extern UART_Handle g_uart0; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void UART0WriteInterruptCallback(void *handle); +void UART0ReadInterruptCallback(void *handle); + +void UART0InterruptErrorCallback(void *handle); + +/* 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/yibaina_3061M/demo/sample_gpio_key/generatecode/system_init.c b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/system_init.c similarity index 66% rename from vendor/yibaina_3061M/demo/sample_gpio_key/generatecode/system_init.c rename to vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/system_init.c index 24a14c9c158800a66611c267cc0c417694a461fc..1b99db736a6b2d359e6247e7403212d4bb1054da 100644 --- a/vendor/yibaina_3061M/demo/sample_gpio_key/generatecode/system_init.c +++ b/vendor/yibaina_3061M/uart_it_Indefinite length/user/generatecode/system_init.c @@ -18,13 +18,14 @@ * @file system_init.c * @author MCU Driver Team * @brief This file contains driver init functions. + * @date 2025-05-08 11:20:52 */ #include "main.h" #include "ioconfig.h" #include "iocmg_ip.h" -#define UART0_BAND_RATE 115200 +#define UART0_BAUD_RATE 115200 BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect) { @@ -46,29 +47,25 @@ BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect) return BASE_STATUS_OK; } -__weak void GPIO_CallBackFunc(void *param) +__weak void UART0InterruptErrorCallback(void *handle) { - GPIO_Handle *handle = (GPIO_Handle *)param; BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_TRNS_IT_ERROR */ + /* USER CODE END UART0_TRNS_IT_ERROR */ } -static void GPIO_Init(void) +__weak void UART0WriteInterruptCallback(void *handle) { - HAL_CRG_IpEnableSet(GPIO2_BASE, IP_CLK_ENABLE); - g_gpio2.baseAddress = GPIO2; - - 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_LOW_LEVEL); - HAL_GPIO_SetIrqType(&g_gpio2, g_gpio2.pins, GPIO_INT_TYPE_RISE_EDGE); - - HAL_GPIO_RegisterCallBack(&g_gpio2, GPIO_PIN_4, GPIO_CallBackFunc); - IRQ_Register(IRQ_GPIO2, HAL_GPIO_IrqHandler, &g_gpio2); - IRQ_SetPriority(IRQ_GPIO2, 1); /* set gpio1 interrupt priority to 1, 1~15. 1 is priority value */ - IRQ_EnableN(IRQ_GPIO2); /* gpio interrupt enable */ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_WRITE_IT_FINISH */ + /* USER CODE END UART0_WRITE_IT_FINISH */ +} - return; +__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) @@ -76,12 +73,12 @@ 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.baudRate = UART0_BAUD_RATE; g_uart0.dataLength = UART_DATALENGTH_8BIT; g_uart0.stopBits = UART_STOPBITS_ONE; g_uart0.parity = UART_PARITY_NONE; - g_uart0.txMode = UART_MODE_BLOCKING; - g_uart0.rxMode = UART_MODE_BLOCKING; + g_uart0.txMode = UART_MODE_INTERRUPT; + g_uart0.rxMode = UART_MODE_INTERRUPT; g_uart0.fifoMode = BASE_CFG_ENABLE; g_uart0.fifoTxThr = UART_FIFODEPTH_SIZE8; g_uart0.fifoRxThr = UART_FIFODEPTH_SIZE8; @@ -89,16 +86,28 @@ static void UART0_Init(void) 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_WRITE_IT_FINISH, (UART_CallbackType)UART0WriteInterruptCallback); + 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, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_UART0); } static void IOConfig(void) { - /* Config PIN21 */ - 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 PIN36 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_0_AS_JTAG_TCK); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_0_AS_JTAG_TCK, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_0_AS_JTAG_TCK, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_0_AS_JTAG_TCK, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_0_AS_JTAG_TCK, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN37 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_1_AS_JTAG_TMS); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_1_AS_JTAG_TMS, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_1_AS_JTAG_TMS, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_1_AS_JTAG_TMS, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_1_AS_JTAG_TMS, DRIVER_RATE_2); /* Output signal edge fast/slow */ /* 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 */ @@ -117,7 +126,6 @@ void SystemInit(void) { IOConfig(); UART0_Init(); - GPIO_Init(); /* USER CODE BEGIN system_init */ /* USER CODE END system_init */ diff --git a/vendor/yibaina_3061M/uart_it_Indefinite length/user/main.c b/vendor/yibaina_3061M/uart_it_Indefinite length/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..f0eaca0e49b9ab8a4262af5c6e9a7e38381295bc --- /dev/null +++ b/vendor/yibaina_3061M/uart_it_Indefinite length/user/main.c @@ -0,0 +1,130 @@ +/** + * @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. + * @date 2025-05-08 11:20:52 + */ + +#include "typedefs.h" +#include "feature.h" +#include "main.h" +#include "debug.h" +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +UART_Handle g_uart0; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ +/* USER CODE END 1 */ + +unsigned char RxBuffer[100]; +unsigned char Index=0; +unsigned char ReceiveBuffer[200]; + +/* +Function name:Uart0_Send_byte() +Description:发送函数 +param:u8 data +retval: +Remarks: + +*/ + +void Uart0_Send_byte(unsigned char ch) +{ + // 等待发送缓冲区空(TXFF标志为0表示可写入) + while (UART0->UART_FR.BIT.txff == 1) { + ; // 空循环等待 + } + + // 写入数据寄存器 + UART0->UART_DR.BIT.data = ch; +} + +/* +Function name:Usart2_Send_str() +Description:串口发送字符串 +param: +retval: +Remarks: + +*/ +void Uart0_Send_str(unsigned char *str) +{ + while((*str)!='\0') + { + Uart0_Send_byte(*str); + str++; + } +} + +void UART0ReadInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART0_READ_IT_FINISH */ + + HAL_UART_ReadIT(&g_uart0, RxBuffer, 1); /* Start receiving again */ + + ReceiveBuffer[Index++]=RxBuffer[0]; + + // FIFO 非空中断状态,状态为0则空闲 + if(UART0->UART_RIS.BIT.rxfneris ==0) + { + ReceiveBuffer[Index]='\0'; + Index=0; + DBG_PRINTF("%s\r\n",ReceiveBuffer); + } + + /* USER CODE END UART0_READ_IT_FINISH */ +} + + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + /* USER CODE END 2 */ + unsigned char buff[]="1234\r\n"; + SystemInit(); + + HAL_UART_ReadIT(&g_uart0, RxBuffer, 1); + /* USER CODE BEGIN 3 */ + /* 建议用户放置初始配置代码 */ + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + /* 建议用户放置周期性执行代码 */ + + + + Uart0_Send_str(buff); + BASE_FUNC_DelayMs(100); + + + /* 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 diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/readme.md b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..c1710108c1422266dc4bf46fb7c37f58a37e14f2 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/readme.md @@ -0,0 +1,31 @@ +# wifi_tenxunyun_mqtt_sample + +**【功能描述】** + +- 基于ECMCU105H/ECBMCU201MPC单板板通过esp32连接腾讯云,通过WIFI进行控制 + +**【环境要求】** + +- esp32通过uart与主板通信,购买链接 https://e.tb.cn/h.6oJ2nMHPk2wnVvj?tk=bcRTVgteKnW + +- 接线方式: + + uart3_rx gpio1_4 --j1_34 + + uart3_tx gpio1_3 --j2_30 + + 3.3v ---J1_15 + + GND---J1_7 + +**【配置方法】** + +- 将user文件夹替换原工程user文件夹即可 +- 在wifi.h文件,修改三元组的宏定义,服务器地址与端口,与订阅和发布的宏定义,根据自己在腾讯云创建的产品信息修改。 + +【操作说明】 + +设置2.4GHz频段热点,名称:WZW 密码:12345678; + +按复位打开腾讯连一连显示设备已连接成功即可。 + diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/feature.h b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/feature.h new file mode 100644 index 0000000000000000000000000000000000000000..9877915e7a734f491d861d104d9548d740872b80 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/feature.h @@ -0,0 +1,120 @@ +/** + * @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. + * @date 2025-04-27 14:34:34 + */ + +#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. */ + +#define MCS_PARAM_CHECK MACRO_ENABLE +#define APT_PARAM_CHECK MACRO_ENABLE +#define ADC_PARAM_CHECK MACRO_ENABLE +#define CAPM_PARAM_CHECK MACRO_ENABLE +#define CRG_PARAM_CHECK MACRO_ENABLE +#define I2C_PARAM_CHECK MACRO_ENABLE +#define UART_PARAM_CHECK MACRO_ENABLE +#define SPI_PARAM_CHECK MACRO_ENABLE +#define TIMER_PARAM_CHECK MACRO_ENABLE +#define IWDG_PARAM_CHECK MACRO_ENABLE +#define WWDG_PARAM_CHECK MACRO_ENABLE +#define GPIO_PARAM_CHECK MACRO_ENABLE +#define GPT_PARAM_CHECK MACRO_ENABLE +#define DMA_PARAM_CHECK MACRO_ENABLE +#define CRC_PARAM_CHECK MACRO_ENABLE +#define CFD_PARAM_CHECK MACRO_ENABLE +#define CMM_PARAM_CHECK MACRO_ENABLE +#define CAN_PARAM_CHECK MACRO_ENABLE +#define FLASH_PARAM_CHECK MACRO_ENABLE +#define PMC_PARAM_CHECK MACRO_ENABLE +#define ACMP_PARAM_CHECK MACRO_ENABLE +#define DAC_PARAM_CHECK MACRO_ENABLE +#define PGA_PARAM_CHECK MACRO_ENABLE +#define IOCMG_PARAM_CHECK MACRO_ENABLE +#define QDM_PARAM_CHECK MACRO_ENABLE + +/* 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/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/main.h b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/main.h new file mode 100644 index 0000000000000000000000000000000000000000..fba9fc4870760b340bf99e5c578ce150960f465d --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/main.h @@ -0,0 +1,61 @@ +/** + * @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. + * @date 2025-04-27 14:34:34 + */ + +/* Define to prevent recursive inclusion ------------------------------------- */ +#ifndef McuMagicTag_SYSTEM_INIT_H +#define McuMagicTag_SYSTEM_INIT_H + +#include "uart.h" +#include "uart_ex.h" +#include "crg.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 + +extern UART_Handle g_uart0; +extern UART_Handle g_uart3; + +BASE_StatusType CRG_Config(CRG_CoreClkSelect *coreClkSelect); +void SystemInit(void); + +void UART3_wifiWriteInterruptCallback(void *handle); +void UART3_wifiReadInterruptCallback(void *handle); + +void UART3_wifiInterruptErrorCallback(void *handle); + +/* 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/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/system_init.c b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/system_init.c new file mode 100644 index 0000000000000000000000000000000000000000..df77c12214b53127cfecdf3b18f5c40f578c234e --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/system_init.c @@ -0,0 +1,166 @@ +/** + * @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. + * @date 2025-04-27 14:34:34 + */ + +#include "main.h" +#include "ioconfig.h" +#include "iocmg_ip.h" + +#define UART0_BAUD_RATE 115200 +#define UART3_BAUD_RATE 115200 + +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 UART0_Init(void) +{ + HAL_CRG_IpEnableSet(UART0_BASE, IP_CLK_ENABLE); /* UART0 clock enable. */ + g_uart0.baseAddress = UART0; + + g_uart0.baudRate = UART0_BAUD_RATE; + g_uart0.dataLength = UART_DATALENGTH_8BIT; + g_uart0.stopBits = UART_STOPBITS_ONE; + g_uart0.parity = UART_PARITY_NONE; + g_uart0.txMode = UART_MODE_BLOCKING; + g_uart0.rxMode = UART_MODE_BLOCKING; + 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); +} + +__weak void UART3_wifiInterruptErrorCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART3_wifiInterruptErrorCallback */ + /* USER CODE END UART3_wifiInterruptErrorCallback */ +} + +__weak void UART3_wifiWriteInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART3_wifiWriteInterruptCallback */ + /* USER CODE END UART3_wifiWriteInterruptCallback */ +} + +__weak void UART3_wifiReadInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + /* USER CODE BEGIN UART3_wifiReadInterruptCallback */ + /* USER CODE END UART3_wifiReadInterruptCallback */ +} + +static void UART3_Init(void) +{ + HAL_CRG_IpEnableSet(UART3_BASE, IP_CLK_ENABLE); /* UART3 clock enable. */ + g_uart3.baseAddress = UART3; + + g_uart3.baudRate = UART3_BAUD_RATE; + g_uart3.dataLength = UART_DATALENGTH_8BIT; + g_uart3.stopBits = UART_STOPBITS_ONE; + g_uart3.parity = UART_PARITY_NONE; + g_uart3.txMode = UART_MODE_INTERRUPT; + g_uart3.rxMode = UART_MODE_INTERRUPT; + g_uart3.fifoMode = BASE_CFG_ENABLE; + g_uart3.fifoTxThr = UART_FIFODEPTH_SIZE8; + g_uart3.fifoRxThr = UART_FIFODEPTH_SIZE8; + g_uart3.hwFlowCtr = BASE_CFG_DISABLE; + g_uart3.handleEx.overSampleMultiple = UART_OVERSAMPLING_16X; + g_uart3.handleEx.msbFirst = BASE_CFG_DISABLE; + HAL_UART_Init(&g_uart3); + HAL_UART_RegisterCallBack(&g_uart3, UART_TRNS_IT_ERROR, (UART_CallbackType)UART3_wifiInterruptErrorCallback); + HAL_UART_RegisterCallBack(&g_uart3, UART_WRITE_IT_FINISH, (UART_CallbackType)UART3_wifiWriteInterruptCallback); + HAL_UART_RegisterCallBack(&g_uart3, UART_READ_IT_FINISH, (UART_CallbackType)UART3_wifiReadInterruptCallback); + IRQ_Register(IRQ_UART3, HAL_UART_IrqHandler, &g_uart3); + IRQ_SetPriority(IRQ_UART3, 1); /* 1 is priority value */ + IRQ_EnableN(IRQ_UART3); +} + +static void IOConfig(void) +{ + /* Config PIN36 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_0_AS_JTAG_TCK); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_0_AS_JTAG_TCK, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_0_AS_JTAG_TCK, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_0_AS_JTAG_TCK, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_0_AS_JTAG_TCK, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN37 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO0_1_AS_JTAG_TMS); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO0_1_AS_JTAG_TMS, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO0_1_AS_JTAG_TMS, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO0_1_AS_JTAG_TMS, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO0_1_AS_JTAG_TMS, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* 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 PIN17 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_3_AS_UART3_TXD); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_3_AS_UART3_TXD, PULL_NONE); /* Pull-up and Pull-down */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_3_AS_UART3_TXD, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_3_AS_UART3_TXD, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_3_AS_UART3_TXD, DRIVER_RATE_2); /* Output signal edge fast/slow */ + /* Config PIN18 */ + HAL_IOCMG_SetPinAltFuncMode(GPIO1_4_AS_UART3_RXD); /* Check function selection */ + HAL_IOCMG_SetPinPullMode(GPIO1_4_AS_UART3_RXD, PULL_UP); /* Pull-up and Pull-down, UART RX recommend PULL_UP */ + HAL_IOCMG_SetPinSchmidtMode(GPIO1_4_AS_UART3_RXD, SCHMIDT_DISABLE); /* Schmitt input on/off */ + HAL_IOCMG_SetPinLevelShiftRate(GPIO1_4_AS_UART3_RXD, LEVEL_SHIFT_RATE_SLOW); /* Output drive capability */ + HAL_IOCMG_SetPinDriveRate(GPIO1_4_AS_UART3_RXD, DRIVER_RATE_2); /* Output signal edge fast/slow */ +} + +void SystemInit(void) +{ + IOConfig(); + UART0_Init(); + UART3_Init(); + + /* USER CODE BEGIN system_init */ + /* USER CODE END system_init */ +} \ No newline at end of file diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.c b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.c new file mode 100644 index 0000000000000000000000000000000000000000..41e4a650958b64bc0a04361a4a174e26c726bd79 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.c @@ -0,0 +1,397 @@ + +/* +**************************************************************************************** +* INCLUDES (头文件包含) +**************************************************************************************** +*/ +#include "MQTT.h" +#include "string.h" + +u8 txbuf[256]={0}; +u8 rxbuf[256]={0}; + + +//连接成功服务器回应 20 02 00 00 +//客户端主动断开连接 e0 00 +const u8 parket_connetAck[] = {0x20,0x02,0x00,0x00};//由于在接收字符时,当我接收到'\0'就转变成' '来存储,所以接收到的回应则是0x20 02 0x20 0x20 +const u8 parket_disconnet[] = {0xe0,0x00}; +const u8 parket_subAck[] = {0x90,0x03}; +const u8 parket_heart[] = {0xc0,0x00}; +const u8 parket_heart_reply[] = {0xd0,0x00};//由于在接收字符时,当我接收到'\0'就转变成' '来存储,所以接收到的回应则是0xd0 0x20 + + +/* +**************************************************************************************** +* LOCAL FUNCTIONS DECLARE (静态函数声明) +**************************************************************************************** +*/ +static void Init(u8 *prx,u16 rxlen,u8 *ptx,u16 txlen); +static u8 Connect(char *ClientID,char *Username,char *Password); +static void Disconnect(void); +static u8 SubscribeTopic(char *topic,u8 qos,u8 whether); +static u8 PublishData(char *topic, char *message, u8 qos); +static void SentHeart(void); +static void SendData(u8* p,u16 len); + +/* +**************************************************************************************** +* LOCAL FUNCTIONS (静态函数) +**************************************************************************************** +*/ +_typdef_mqtt _mqtt = +{ + 0,0, + 0,0, + Init, + Connect, + Disconnect, + SubscribeTopic, + PublishData, + SentHeart, + SendData, +}; + + +static u8 BYTE1(int num) +{ + return (u8)((num&0xFF00)>>8); +} +static u8 BYTE0(int num) +{ + return (u8)(num&0xFF); +} + +/* +**************************************************************************************** +* Function: Init +* Description: MQTT初始化 +* Input: None +* Output: None +* Return: None +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static void Init(u8 *prx,u16 rxlen,u8 *ptx,u16 txlen) +{ + _mqtt.rxbuf = prx;_mqtt.rxlen = rxlen; + _mqtt.txbuf = ptx;_mqtt.txlen = txlen; + +// memset(_mqtt.rxbuf,0,_mqtt.rxlen); +// memset(_mqtt.txbuf,0,_mqtt.txlen); +// +// //无条件先主动断开,发送4次,保证能断开 +// _mqtt.Disconnect();BASE_FUNC_DelayMs(100); +// _mqtt.Disconnect();BASE_FUNC_DelayMs(100); +// _mqtt.Disconnect();BASE_FUNC_DelayMs(100); +// _mqtt.Disconnect();BASE_FUNC_DelayMs(100); +} + +/* +**************************************************************************************** +* Function: Connect +* Description: 连接服务器的打包函数 +* Input: ClientID:客户端标识符 + Username:用户名 + Password:密码 +* Output: None +* Return: 1成功 0失败 +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static __UINT8_TYPE__ Connect(char *ClientID,char *Username,char *Password) +{ + int ClientIDLen = strlen(ClientID); + int UsernameLen = strlen(Username); + int PasswordLen = strlen(Password); + int DataLen; + _mqtt.txlen=0; + //Variable Header(可变报头)+Payload(有效负荷) 每个字段包含两个字节的长度标识 + DataLen = 10 + (ClientIDLen+2) + (UsernameLen+2) + (PasswordLen+2); + + //固定报头 + //控制报文类型 + _mqtt.txbuf[_mqtt.txlen++] = 0x10; //MQTT Message Type CONNECT + //剩余长度(不包括固定头部) + do + { + u8 encodedByte = DataLen % 128; + DataLen = DataLen / 128; + // if there are more data to encode, set the top bit of this byte + if ( DataLen > 0 ) + encodedByte = encodedByte | 128; + _mqtt.txbuf[_mqtt.txlen++] = encodedByte; + }while ( DataLen > 0 ); + + //可变报头 + //协议名 + _mqtt.txbuf[_mqtt.txlen++] = 0; // Protocol Name Length MSB + _mqtt.txbuf[_mqtt.txlen++] = 4; // Protocol Name Length LSB + _mqtt.txbuf[_mqtt.txlen++] = 'M'; // ASCII Code for M + _mqtt.txbuf[_mqtt.txlen++] = 'Q'; // ASCII Code for Q + _mqtt.txbuf[_mqtt.txlen++] = 'T'; // ASCII Code for T + _mqtt.txbuf[_mqtt.txlen++] = 'T'; // ASCII Code for T + //协议级别 + _mqtt.txbuf[_mqtt.txlen++] = 4; // MQTT Protocol version = 4 + //连接标志 + _mqtt.txbuf[_mqtt.txlen++] = 0xc2; // conn flags + //心跳间隔时间 + _mqtt.txbuf[_mqtt.txlen++] = 0x01; // Keep-alive Time Length MSB + _mqtt.txbuf[_mqtt.txlen++] = 0xF4; // Keep-alive Time Length LSB 500S心跳包 + + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(ClientIDLen);// Client ID length MSB + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(ClientIDLen);// Client ID length LSB + memcpy(&_mqtt.txbuf[_mqtt.txlen],ClientID,ClientIDLen); + _mqtt.txlen += ClientIDLen; + + if(UsernameLen > 0) + { + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(UsernameLen); //username length MSB + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(UsernameLen); //username length LSB + memcpy(&_mqtt.txbuf[_mqtt.txlen],Username,UsernameLen); + _mqtt.txlen += UsernameLen; + } + + if(PasswordLen > 0) + { + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(PasswordLen); //password length MSB + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(PasswordLen); //password length LSB + memcpy(&_mqtt.txbuf[_mqtt.txlen],Password,PasswordLen); + _mqtt.txlen += PasswordLen; + } + + //printf("%s",_mqtt.txbuf); + _mqtt.SendData(_mqtt.txbuf,_mqtt.txlen); + + u16 time=0; + while(!esp32.tc_flag)//等待传输完成标志 + { + BASE_FUNC_DelayMs(1); + if(++time>500) //超时 + break; + } + if(esp32.tc_flag) + { + esp32.tc_flag=0;//清标志 + //if(rxbuf[0]==parket_connetAck[0] && rxbuf[1]==parket_connetAck[1]) //连接成功 + if(esp32.ReceiveBuffer[0]==parket_connetAck[0] && esp32.ReceiveBuffer[1]==parket_connetAck[1]) //连接成功 + { + return 1;//连接成功 + } + } + + return 0; + + +} + +/* +**************************************************************************************** +* Function: SubscribeTopic +* Description: MQTT订阅/取消订阅数据打包并发送 +* Input: topic 主题 + qos 消息等级 + 0:最多一次,即:<=1 + 1:至少一次,即:>=1 + 2:一次,即:=1 + whether 1订阅/0取消订阅请求包 +* Output: None +* Return: 1成功 0失败 +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static u8 SubscribeTopic(char *topic,u8 qos,u8 whether) +{ + _mqtt.txlen=0; + int topiclen = strlen(topic); + + int DataLen = 2 + (topiclen+2) + (whether?1:0);//可变报头的长度(2字节)加上有效载荷的长度 + //固定报头 + //控制报文类型 + if(whether) _mqtt.txbuf[_mqtt.txlen++] = 0x82; //消息类型和标志订阅 + else _mqtt.txbuf[_mqtt.txlen++] = 0xA2; //取消订阅 + + //剩余长度 + do + { + u8 encodedByte = DataLen % 128; + DataLen = DataLen / 128; + // if there are more data to encode, set the top bit of this byte + if ( DataLen > 0 ) + encodedByte = encodedByte | 128; + _mqtt.txbuf[_mqtt.txlen++] = encodedByte; + }while ( DataLen > 0 ); + + //可变报头 + _mqtt.txbuf[_mqtt.txlen++] = 0; //消息标识符 MSB + _mqtt.txbuf[_mqtt.txlen++] = 0x01; //消息标识符 LSB + //有效载荷 + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(topiclen);//主题长度 MSB + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(topiclen);//主题长度 LSB + memcpy(&_mqtt.txbuf[_mqtt.txlen],topic,topiclen); + _mqtt.txlen += topiclen; + + if(whether) + { + _mqtt.txbuf[_mqtt.txlen++] = qos;//QoS级别 + } + + _mqtt.SendData(_mqtt.txbuf,_mqtt.txlen); + + u16 time=0; + while(!esp32.tc_flag)//等待传输完成标志 + { + BASE_FUNC_DelayMs(1); + if(++time>500) //超时 + break; + + } + if(esp32.tc_flag) + { + esp32.tc_flag=0;//清标志 + //if(_mqtt.rxbuf[0]==parket_subAck[0] && _mqtt.rxbuf[1]==parket_subAck[1]) //订阅成功 + if(esp32.ReceiveBuffer[0]==parket_subAck[0] && esp32.ReceiveBuffer[1]==parket_subAck[1]) //订阅成功 + { + return 1;//订阅成功 + } + } + + return 0; + +} + +/* +**************************************************************************************** +* Function: PublishData +* Description: MQTT发布数据打包并发送 +* Input: topic 主题 + message 消息 + qos 消息等级 +* Output: None +* Return: 数据包长度 +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static __UINT8_TYPE__ PublishData(char *topic, char *message, __UINT8_TYPE__ qos) +{ + int topicLength = strlen(topic); + int messageLength = strlen(message); + static u16 id=0; + int DataLen; + _mqtt.txlen=0; + //有效载荷的长度这样计算:用固定报头中的剩余长度字段的值减去可变报头的长度 + //QOS为0时没有标识符 + //数据长度 主题名 报文标识符 有效载荷 + if(qos) DataLen = (2+topicLength) + 2 + messageLength; + else DataLen = (2+topicLength) + messageLength; + + //固定报头 + //控制报文类型 + _mqtt.txbuf[_mqtt.txlen++] = 0x30; // MQTT Message Type PUBLISH + + //剩余长度 + do + { + u8 encodedByte = DataLen % 128; + DataLen = DataLen / 128; + // if there are more data to encode, set the top bit of this byte + if ( DataLen > 0 ) + encodedByte = encodedByte | 128; + _mqtt.txbuf[_mqtt.txlen++] = encodedByte; + }while ( DataLen > 0 ); + + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(topicLength);//主题长度MSB + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(topicLength);//主题长度LSB + memcpy(&_mqtt.txbuf[_mqtt.txlen],topic,topicLength);//拷贝主题 + _mqtt.txlen += topicLength; + + //报文标识符 + if(qos) + { + _mqtt.txbuf[_mqtt.txlen++] = BYTE1(id); + _mqtt.txbuf[_mqtt.txlen++] = BYTE0(id); + id++; + } + memcpy(&_mqtt.txbuf[_mqtt.txlen],message,messageLength); + _mqtt.txlen += messageLength; + + _mqtt.SendData(_mqtt.txbuf,_mqtt.txlen); + return _mqtt.txlen; +} + +/* +**************************************************************************************** +* Function: SentHeart +* Description: 发送心跳 +* Input: None +* Output: None +* Return: None +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static void SentHeart(void) +{ + _mqtt.SendData((u8 *)parket_heart,sizeof(parket_heart)); +} + +/* +**************************************************************************************** +* Function: Disconnect +* Description: 发送Disconnect报文 +* Input: None +* Output: None +* Return: None +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static void Disconnect(void) +{ + _mqtt.SendData((u8 *)parket_disconnet,sizeof(parket_disconnet)); +} + +/* +**************************************************************************************** +* Function: SendData +* Description: 函数功能:MQTT数据包发送函数 +* Input: p指向待发送的数据包,数据包数据长度 +* Output: None +* Return: None +* Author: weihaoMo +* Others: None +* Date of completion: 2019-11-29 +* Date of last modify: 2019-11-29 +**************************************************************************************** +*/ +static void SendData(u8* p,u16 len) +{ + while(len--) + { + while(UART3->UART_FR.BIT.txff == 1); //等待发送缓冲区为空 + UART3->UART_DR.BIT.data=*p; + p++; + } +} +/* +**************************************************************************************** +* PUBLIC FUNCTIONS (全局函数) +**************************************************************************************** +*/ + + diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.h b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.h new file mode 100644 index 0000000000000000000000000000000000000000..e8350034accdc631fbc0606e9896e3bd9de0cd41 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/MQTT.h @@ -0,0 +1,71 @@ +#ifndef _MQTT_H_ +#define _MQTT_H_ + +#ifdef __cplusplus + extern "C" { +#endif + + +/* +**************************************************************************************** +* INCLUDES (头文件包含) +**************************************************************************************** +*/ +#include "main.h" +#include "wifi.h" +/* +**************************************************************************************** +* TYPEDEFS (数据类型重定义) +**************************************************************************************** +*/ +typedef struct +{ + u8 *rxbuf;u16 rxlen; + u8 *txbuf;u16 txlen; + + void (*Init)(u8 *prx,u16 rxlen,u8 *ptx,u16 txlen); + u8 (*Connect)(char *ClientID,char *Username,char *Password); + void (*Disconnect)(void); + u8 (*SubscribeTopic)(char *topic,u8 qos,u8 whether); + u8 (*PublishData)(char *topic, char *message, u8 qos); + void (*SendHeart)(void); + void (*SendData)(u8* p,u16 len); +}_typdef_mqtt; + +/* +**************************************************************************************** +* EXTERNAL VARIABLES (外部变量) +**************************************************************************************** +*/ +extern u8 txbuf[256]; +extern u8 rxbuf[256]; +extern _typdef_mqtt _mqtt; + +/* +**************************************************************************************** +* CONSTANTS (常量) +**************************************************************************************** +*/ + + +/* +**************************************************************************************** +* MACROS (宏定义) +**************************************************************************************** +*/ + + +/* +**************************************************************************************** +* PUBLIC FUNCTIONS DECLARE (声明全局函数) +**************************************************************************************** +*/ + + + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.c b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.c new file mode 100644 index 0000000000000000000000000000000000000000..c695a8d9e1cab70cb0dd584887705454dc4a8889 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.c @@ -0,0 +1,413 @@ +#include "wifi.h" +#include "string.h" +#include "debug.h" + +#include "MQTT.h" + +#include +//uart3_rx gpio1_4 --j1_34 +//uart3_tx gpio1_3 --j2_30 + + +U8 U3RxBuffer[100]; +U8 gucDecoderIndex = 0; + +ESP32_STRUCT esp32; + +/** + * @brief User-defined read completion interrupt callback function. + * @param UART_Handle UART handle. + * @retval None. + */ +void UART3_wifiReadInterruptCallback(void *handle) +{ + BASE_FUNC_UNUSED(handle); + unsigned char data = 0; + HAL_UART_ReadIT(&g_uart3, U3RxBuffer, 1); /* Start receiving again */ + + if(U3RxBuffer[0]==0 || U3RxBuffer[0]=='\0') //遇到没数据,或者‘\0’补空格 + { + esp32.ReceiveBuffer[esp32.gucDecoderIndex++]=' '; + } + else + { + esp32.ReceiveBuffer[esp32.gucDecoderIndex++]=U3RxBuffer[0]; + } + + // FIFO 非空中断状态,状态为0则空闲 + if(UART3->UART_RIS.BIT.rxfneris ==0) + { + esp32.ReceiveBuffer[esp32.gucDecoderIndex]='\0'; + esp32.tc_flag=1; + esp32.gucDecoderIndex=0; + DBG_PRINTF("%s\r\n",esp32.ReceiveBuffer); + + } + + +} + + +/** + * @brief 通过UART3发送单个字节 + * @param ch: 要发送的字符( + * @note 阻塞式发送,会一直等待直到发送缓冲区可用 + */ +// void U3SendCh(unsigned int ch) +// { +// // 等待发送缓冲区空(TXFF标志为0表示可写入) +// while (UART3->UART_FR.BIT.txff == 1) { +// ; // 空循环等待 +// } + +// // 写入数据寄存器(强制截取低8位) +// UART3->UART_DR.BIT.data = (unsigned char)ch; +// } + +void U3SendCh(unsigned char ch) +{ + // 等待发送缓冲区空(TXFF标志为0表示可写入) + while (UART3->UART_FR.BIT.txff == 1) { + ; // 空循环等待 + } + + // 写入数据寄存器 + UART3->UART_DR.BIT.data = ch; +} + + +/** + * @brief 通过UART3发送字符串(以'\0'结尾) + * @param pBuffer: 字符串指针(8位无符号数组) + * @note 逐字节发送,直到遇到字符串结束符'\0' + */ +void WiFiSend(u8* pBuffer) +{ + // 遍历字符串直到结束符 + while(*pBuffer != '\0') + { + // 调用单字节发送函数 + U3SendCh(*pBuffer); + + // 移动到下一个字符 + pBuffer++; + } +} + + + + +/* +Function name:ESP32_SendAt +Description:发送AT指令并判断ESP32回应词 +param:u8 *cmd 发送AT指令 + u8 *respond需要判断的回应词 +retval:u8 0:成功 1:失败 +Remarks: +AT执行成功:OK 失败:ERRO +*/ + +u8 ESP32_SendAt(u8 *cmd,u8 *respond) +{ + //1.发送AT指令 + WiFiSend(cmd); + BASE_FUNC_DelayMs(300); + //2.判断回应词 + while(1) + { + //等待ESP32数据接收完成 + while(!esp32.tc_flag); + esp32.tc_flag=0; + if(strstr((const char*)esp32.ReceiveBuffer,(const char*)respond)!=NULL) + { + + return 0; + } + else + { + return 1; + } + } +} + + + +u8 ESP32_Init(void) +{ + + //2.ESP32初始化 + WiFiSend((u8*)"+++");//退出透传,准备发送AT指令设置ESP32 + BASE_FUNC_DelayMs(300); + WiFiSend((u8*)"AT\r\n");//发送一条正确的AT指令跳过格式错误 + BASE_FUNC_DelayMs(300); + WiFiSend((u8*)"AT+RESTORE\r\n");//恢复出厂设置 + BASE_FUNC_DelayMs(1000); + + if( ESP32_SendAt((u8 *)"AT+CWMODE=1\r\n",(u8 *)"OK")!=0) + { + DBG_PRINTF(" set up client Faile\r\n"); + return 1; + } + DBG_PRINTF("set up client Success\r\n"); + + + if( ESP32_SendAt((u8 *)"AT+CIPMODE=1\r\n",(u8 *)"OK")!=0) + { + DBG_PRINTF("Setti transparent transmission faile\r\n"); + return 2; + } + + DBG_PRINTF("Setti transparent transmission Success\r\n"); + + DBG_PRINTF("ESP32 TCP init Success\r\n"); + + return 0; + +} + + + + +/* +Function name:ESP32_ConnectAp +Description:ESP32连接路由器 +param:u8 *ssid WIFI账户名 + u8 *pwd WIFI密码 +retval:u8 0:成功 1:失败 +Remarks: +AT执行成功:OK 失败:ERRO +*/ +u8 ESP32_ConnectAp(u8 *ssid,u8 *pwd) +{ + + //使用AT指令向ESP32发送wifi账号和wifi密码 + /*方法一*/ +// u8 wifi_buff[100]= "AT+CWJAP=\""; +// strcat((char *)wifi_buff,(char *)ssid); +// strcat((char *)wifi_buff,"\",\""); +// strcat((char *)wifi_buff,(char *)pwd); +// strcat((char *)wifi_buff,"\"\r\n"); + /*方法二*/ + u8 wifi_buff[100]; + + sprintf((char *)wifi_buff,"AT+CWJAP=\"%s\",\"%s\"\r\n",ssid,pwd); + + WiFiSend(wifi_buff);//发送连接AP指令 + while(1) + { + while(!esp32.tc_flag);//等待ESP32数据接收完成 + esp32.tc_flag = 0; + + if(strstr((const char *)esp32.ReceiveBuffer,"OK") != NULL) + { + + DBG_PRINTF("WIFI AP Connection success\r\n"); + return 0; + } + if(strstr((const char *)esp32.ReceiveBuffer,"ERROR") != NULL) + { + + DBG_PRINTF("WIFI AP Connection fail\r\n"); + return 1; + } + } + +} + + +/* +Function name:ESP32_ConnectSer +Description:ESP32连接服务器 +param: + u8 *ip 服务器地址 + u8 *port 远端端口号 +retval:u8 0:成功 1:失败 +Remarks: + +*/ +u8 ESP32_ConnectSer(u8 *ip,u8 *port) +{ + u8 wifi_buff[200]={0}; + sprintf((char *)wifi_buff,"AT+CIPSTART=\"TCP\",\"%s\",%s\r\n",ip,port); + + WiFiSend(wifi_buff);//发送连接服务器指令\ + + while(1) + { + while(!esp32.tc_flag); + + esp32.tc_flag=0; + if(strstr((const char*)esp32.ReceiveBuffer,"OK")!=NULL) + { + + DBG_PRINTF("Server connection successful\r\n"); + return 0; + } + if(strstr((const char*)esp32.ReceiveBuffer,"ERROR")!=NULL) + { + + DBG_PRINTF("server connection failed\r\n"); + return 1; + + } + } +} + + + +/* +Function name:ESP32_Start_Connect +Description:ESP32开始配网 +param: +retval:u8 0:成功 1:失败 +Remarks: + +*/ + +u8 ESP32_Start_Connect(void) +{ + u8 ret = 0; + if(ESP32_Init()==0)//ESP32初始化 + { + if(ESP32_ConnectAp((u8 *)"WZW",(u8 *)"12345678")==0)//ESP32连接AP + { + if(ESP32_ConnectSer((u8 *)ServerAddress,(u8 *)ServerPort)==0)//ESP32连接腾讯云服务器 + { + ESP32_SendAt((u8 *)"AT+CIPSEND\r\n",(u8 *)"OK");//进入透传 + + _mqtt.Init(rxbuf,0,txbuf,0);//初始化MQTT框架 + + ret=_mqtt.Connect(Client,User,Pass); + if(ret) + { + DBG_PRINTF("MQTT Tencent Cloud Success\r\n"); + ret = _mqtt.SubscribeTopic(SubTopic,0,1); + + DBG_PRINTF("ret=%d\r\n",ret); + if(ret) + { + DBG_PRINTF("Subscription successful\r\n"); + } + else + { + DBG_PRINTF("Subscription failed\r\n"); + } + + } + else + DBG_PRINTF("MQTT connection to Tencent Cloud failed\r\n"); + } + } + } +} + + + + +/*t +Function name:ESP32_Control +Description:接收服务器数据,执行对应功能 +param: +retval: +Remarks: +接收服务器的数据,会保存到exp32.buff里面 + +*/ + + +void ESP32_Control(void) +{ + + + //服务器控制开关电机 + if(strstr((const char*)esp32.ReceiveBuffer,"\"OpenMotor\":1")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Motor Open\r\n"); + + + } + + if(strstr((const char*)esp32.ReceiveBuffer,"\"OpenMotor\":0")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Motor close\r\n"); + + } + + if(strstr((const char*)esp32.ReceiveBuffer,"\"OpenMotor\":1")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Motor Open\r\n"); + + + } + //服务器控制电机转速 + + if(strstr((const char*)esp32.ReceiveBuffer,"\"SpeedControl\":1")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Level 1\r\n"); + + } + if(strstr((const char*)esp32.ReceiveBuffer,"\"SpeedControl\":2")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Level 2\r\n"); + + } + if(strstr((const char*)esp32.ReceiveBuffer,"\"SpeedControl\":3")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Level 3\r\n"); + + } + if(strstr((const char*)esp32.ReceiveBuffer,"\"SpeedControl\":4")!=NULL) + { + memset(esp32.ReceiveBuffer,0,sizeof esp32.ReceiveBuffer); + DBG_PRINTF("Level 4\r\n"); + + } + + + + //上传速度值 + + ESP32_DatatoServer((u8 *)"Speed",50.0); + + + +} + + + +/* +Function name:ESP32_DatatoServer +Description:发送服务器数据 +param: u8 *mark 功能标识 +retval: u8 *value 功能数值 +Remarks: +接收服务器的数据,会保存到exp32.buff里面 + +*/ + +void ESP32_DatatoServer(u8 *mark,u8 value) +{ + u8 message_buff[300]={0}; + sprintf((char *)message_buff,"{\"method\":\"report\",\"clientToken\":\"v2179483179IgNsi::h6-Td$aDz\",\"params\":{\"%s\":%d}}",mark,value); + _mqtt.PublishData(PupTopic,(char *)message_buff,0); +} + + + + + + + + + + + + + + diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.h b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.h new file mode 100644 index 0000000000000000000000000000000000000000..902648ae416e59c371de582717f8e1ca18c45359 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/generatecode/wifi/wifi.h @@ -0,0 +1,71 @@ +#ifndef __WIFI_C__ +#define __WIFI_C__ + +#include "main.h" + +typedef signed char INT8S, S8; +typedef unsigned char BYTE, INT8U, U8, u8; +typedef signed short int INT16S, S16; +typedef unsigned short int WORD, INT16U, U16, u16; +typedef signed long LONG, INT32S, S32; +typedef unsigned long DWORD, INT32U, U32, u32; + +//三元组宏定义 +#define Client "D5MLGDVORYMotorControl" //ID +#define User "D5MLGDVORYMotorControl;12010126;IFCJK;1745908540" //用户名称 +#define Pass "5eec1815a1400df602c3d26ce4b3e60a3c89d164428a77720b64a37969cdbde5;hmacsha256" //密钥 + +#define ServerAddress "D5MLGDVORY.iotcloud.tencentdevices.com" //服务器地址 +#define ServerPort "1883" //端口 + +#define SubTopic "$thing/down/property/D5MLGDVORY/MotorControl" //订阅 +#define PupTopic "$thing/up/property/D5MLGDVORY/MotorControl" //发布 + +extern U8 U3RxBuffer[100]; + + + + +typedef struct +{ + u8 ReceiveBuffer[3048]; //保存接收ESP32/服务器数据 + U16 gucDecoderIndex; //决定接收数据的长度 + u8 tc_flag; //传输完成标志位 + u8 time[50]; //保存时间 + u8 t_len; + +}ESP32_STRUCT; + +extern ESP32_STRUCT esp32; + + + + + +void WiFiSend(u8* pBuffer); + +u8 ESP32_Init(void); +u8 ESP32_ConnectAp(u8 *ssid,u8 *pwd); +u8 ESP32_Start_Connect(void); +void ESP32_Control(void); +void ESP32_DatatoServer(u8 *mark,u8 value); + + + + + + + + + + + +#endif + + + + + + + + diff --git a/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/main.c b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/main.c new file mode 100644 index 0000000000000000000000000000000000000000..d196b1066182515e249a5d6e1e414816ae7167c6 --- /dev/null +++ b/vendor/yibaina_3061M/wifi_tenxunyun_mqtt_sample/user/main.c @@ -0,0 +1,74 @@ +/** + * @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. + * @date 2025-04-27 14:34:34 + */ + +#include "typedefs.h" +#include "feature.h" +#include "main.h" +#include "wifi.h" +#include "debug.h" + + + +/* USER CODE BEGIN 0 */ +/* USER CODE 区域内代码不会被覆盖,区域外会被生成的默认代码覆盖(其余USER CODE 区域同理) */ +/* 建议用户放置头文件 */ +/* USER CODE END 0 */ +UART_Handle g_uart0; +UART_Handle g_uart3; +/* USER CODE BEGIN 1 */ +/* 建议用户定义全局变量、结构体、宏定义或函数声明等 */ +/* USER CODE END 1 */ + +int main(void) +{ + /* USER CODE BEGIN 2 */ + /* 建议用户放置初始化代码或启动代码等 */ + + /* USER CODE END 2 */ + SystemInit(); + /* USER CODE BEGIN 3 */ + /* 建议用户放置初始配置代码 */ + + HAL_UART_ReadIT(&g_uart3, U3RxBuffer, 1); + + ESP32_Start_Connect();//开始配网 + + /* USER CODE END 3 */ + while (1) { + /* USER CODE BEGIN 4 */ + // WiFiSend("1111"); + BASE_FUNC_DelayMs(100); + ESP32_Control(); + + /* 建议用户放置周期性执行代码 */ + /* 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