修正电流限幅

This commit is contained in:
BoomPC 2024-12-02 02:45:48 +08:00
parent 721796e105
commit 58e529da77
73 changed files with 1920 additions and 12247 deletions

View File

@ -23,7 +23,7 @@
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.1984140111" name="Floating-point unit" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv4-sp-d16" valueType="enumerated"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.1984140111" name="Floating-point unit" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv4-sp-d16" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.1267087860" name="Floating-point ABI" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.1267087860" name="Floating-point ABI" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.1450558436" name="Board" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.1450558436" name="Board" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.1879587253" name="Defaults" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Debug || true || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32G431VBTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../USB_Device/App | ../USB_Device/Target | ../Drivers/STM32G4xx_HAL_Driver/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32G4xx/Include | ../Drivers/CMSIS/Include || || || USE_HAL_DRIVER | STM32G431xx || || USB_Device | Drivers | Core/Startup | Middlewares | Core || || || ${workspace_loc:/${ProjName}/STM32G431VBTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.1879587253" name="Defaults" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Debug || true || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32G431VBTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy | ../Drivers/CMSIS/Device/ST/STM32G4xx/Include | ../Drivers/CMSIS/Include || || || USE_HAL_DRIVER | STM32G431xx || || Drivers | Core/Startup | Core || || || ${workspace_loc:/${ProjName}/STM32G431VBTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.703046927" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="168" valueType="string"/> <option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.703046927" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="168" valueType="string"/>
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.1574791951" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/> <targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.1574791951" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/>
<builder buildPath="${workspace_loc:/BoooomFOC_STSPIN32G4_EVB}/Debug" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1456362012" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/> <builder buildPath="${workspace_loc:/BoooomFOC_STSPIN32G4_EVB}/Debug" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1456362012" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/>
@ -44,12 +44,8 @@
</option> </option>
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths.373873462" name="Include paths (-I)" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths" valueType="includePath"> <option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths.373873462" name="Include paths (-I)" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths" valueType="includePath">
<listOptionValue builtIn="false" value="../Core/Inc"/> <listOptionValue builtIn="false" value="../Core/Inc"/>
<listOptionValue builtIn="false" value="../USB_Device/App"/>
<listOptionValue builtIn="false" value="../USB_Device/Target"/>
<listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc"/> <listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc"/>
<listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy"/> <listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy"/>
<listOptionValue builtIn="false" value="../Middlewares/ST/STM32_USB_Device_Library/Core/Inc"/>
<listOptionValue builtIn="false" value="../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc"/>
<listOptionValue builtIn="false" value="../Drivers/CMSIS/Device/ST/STM32G4xx/Include"/> <listOptionValue builtIn="false" value="../Drivers/CMSIS/Device/ST/STM32G4xx/Include"/>
<listOptionValue builtIn="false" value="../Drivers/CMSIS/Include"/> <listOptionValue builtIn="false" value="../Drivers/CMSIS/Include"/>
</option> </option>
@ -78,9 +74,7 @@
</toolChain> </toolChain>
</folderInfo> </folderInfo>
<sourceEntries> <sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="USB_Device"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Middlewares"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Drivers"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Drivers"/>
</sourceEntries> </sourceEntries>
</configuration> </configuration>
@ -109,7 +103,7 @@
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.492494204" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv4-sp-d16" valueType="enumerated"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.492494204" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv4-sp-d16" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.1425506387" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.1425506387" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.1498232860" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.1498232860" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.268333874" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Release || false || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32G431VBTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../USB_Device/App | ../USB_Device/Target | ../Drivers/STM32G4xx_HAL_Driver/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32G4xx/Include | ../Drivers/CMSIS/Include || || || USE_HAL_DRIVER | STM32G431xx || || USB_Device | Drivers | Core/Startup | Middlewares | Core || || || ${workspace_loc:/${ProjName}/STM32G431VBTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/> <option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.268333874" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Release || false || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32G431VBTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc | ../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy | ../Drivers/CMSIS/Device/ST/STM32G4xx/Include | ../Drivers/CMSIS/Include || || || USE_HAL_DRIVER | STM32G431xx || || Drivers | Core/Startup | Core || || || ${workspace_loc:/${ProjName}/STM32G431VBTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.1724099006" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="168" valueType="string"/> <option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.1724099006" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="168" valueType="string"/>
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.1284979115" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/> <targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.1284979115" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/>
<builder buildPath="${workspace_loc:/BoooomFOC_STSPIN32G4_EVB}/Release" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1943144139" managedBuildOn="true" name="Gnu Make Builder.Release" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/> <builder buildPath="${workspace_loc:/BoooomFOC_STSPIN32G4_EVB}/Release" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1943144139" managedBuildOn="true" name="Gnu Make Builder.Release" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/>
@ -126,12 +120,8 @@
</option> </option>
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths.2026911592" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths" valueType="includePath"> <option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths.2026911592" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.tool.c.compiler.option.includepaths" valueType="includePath">
<listOptionValue builtIn="false" value="../Core/Inc"/> <listOptionValue builtIn="false" value="../Core/Inc"/>
<listOptionValue builtIn="false" value="../USB_Device/App"/>
<listOptionValue builtIn="false" value="../USB_Device/Target"/>
<listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc"/> <listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc"/>
<listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy"/> <listOptionValue builtIn="false" value="../Drivers/STM32G4xx_HAL_Driver/Inc/Legacy"/>
<listOptionValue builtIn="false" value="../Middlewares/ST/STM32_USB_Device_Library/Core/Inc"/>
<listOptionValue builtIn="false" value="../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc"/>
<listOptionValue builtIn="false" value="../Drivers/CMSIS/Device/ST/STM32G4xx/Include"/> <listOptionValue builtIn="false" value="../Drivers/CMSIS/Device/ST/STM32G4xx/Include"/>
<listOptionValue builtIn="false" value="../Drivers/CMSIS/Include"/> <listOptionValue builtIn="false" value="../Drivers/CMSIS/Include"/>
</option> </option>
@ -160,9 +150,7 @@
</toolChain> </toolChain>
</folderInfo> </folderInfo>
<sourceEntries> <sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="USB_Device"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Middlewares"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Drivers"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Drivers"/>
</sourceEntries> </sourceEntries>
</configuration> </configuration>

View File

@ -0,0 +1,7 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<clangFormatSettings>
<option name="ENABLED" value="true" />
</clangFormatSettings>
</code_scheme>
</component>

View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

File diff suppressed because one or more lines are too long

View File

@ -3,141 +3,165 @@
// //
#include "APP_Main.h" #include "APP_Main.h"
#include "APP_Task.h"
#include "Controller/Controller.h" #include "Controller/Controller.h"
#include "PreDrive.h" #include "PreDrive.h"
#include "controller.h"
#include "encoder.h"
#include "foc.h"
#include "pwm_curr.h"
#include "usr_config.h"
float32_t NowAngle; volatile uint32_t SystickCount = 0;
tData Data; //uint8_t RxBuffer[2];//接收数据
//float32_t NowAngle;
void APP_Init() uint8_t USART1_IRQHandler_Status;
{
void APP_Init() {
USR_CONFIG_set_default_config();
USR_CONFIG_read_config();
__HAL_SPI_ENABLE(&hspi1); __HAL_SPI_ENABLE(&hspi1);
HAL_Delay(10); HAL_Delay(10);
Data.Angle.EncoderModel = MT6816; // Data.Angle.EncoderModel = MT6816;
Data_Init(&Data); // Data_Init(&Data);
// NowAngle = Data.Angle.getAngle(); // NowAngle = Data.Angle.getAngle();
//<2F>???启内部运<E983A8>???
//开启内部运放
HAL_OPAMP_Start(&hopamp1); HAL_OPAMP_Start(&hopamp1);
HAL_OPAMP_Start(&hopamp2); HAL_OPAMP_Start(&hopamp2);
HAL_OPAMP_Start(&hopamp3); HAL_OPAMP_Start(&hopamp3);
HAL_Delay(10); HAL_Delay(10);
while (InteriorADC_Init()); // while (InteriorADC_Init())
HAL_ADC_Start_DMA(&hadc1, (uint32_t *) adc1_RegularBuf, 2); HAL_ADC_Start_DMA(&hadc1, (uint32_t *) adc1_RegularBuf, 2);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1); // HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2); // HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3); // HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1); // HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1);
HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_2); // HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_2);
HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_3); // HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_3);
HAL_Delay(10); // HAL_Delay(10);
__HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE); // __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
HAL_Delay(10); // HAL_Delay(10);
PreDrive_Init(); // PreDrive_Init();
GPIOE->BSRR = 1 << 7; // GPIOE->BSRR = 1 << 7;
HAL_Delay(10); // HAL_Delay(10);
TIM1->CCR1 = 0; TIM1->CCR1 = 0;
TIM1->CCR2 = 0; TIM1->CCR2 = 0;
TIM1->CCR3 = 0; TIM1->CCR3 = 0;
HAL_Delay(10);
MCT_init();
FOC_init();
PWMC_init();
ENCODER_init();
CONTROLLER_init();
__HAL_ADC_DISABLE_IT(&hadc1, ADC_IT_JEOS);//关闭ADC1的中断避免ADC1_2_IRQHandler触发两次
__HAL_ADC_DISABLE_IT(&hadc2, ADC_IT_JEOS);//关闭ADC1的中断避免ADC1_2_IRQHandler触发两次
for (uint8_t i = 0, j = 0; i < 250; i++) {
if (Foc.v_bus_filt > 20) {
if (++j > 20) {
break;
}
}
HAL_Delay(2);
}
while (PWMC_CurrentReadingPolarization()) {
StatuswordNew.errors.adc_selftest_fatal = 1;
}
__HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
__HAL_ADC_ENABLE_IT(&hadc1, ADC_IT_JEOS);//关闭ADC1的中断避免ADC1_2_IRQHandler触发两次
// MCT_set_state(IDLE);
} }
uint16_t ADC_VAL1, ADC_VAL2; uint16_t ADC_VAL1, ADC_VAL2;
//MCU内部温度传感器 //MCU内部温度传感器
#define TS_CAL1 ((uint16_t*) ((uint32_t) 0x1FFF75A8)) // 30摄氏度时的MCU内部温度传感器校准值 #define TS_CAL1 ((uint16_t *) ((uint32_t) 0x1FFF75A8))// 30摄氏度时的MCU内部温度传感器校准值
#define TS_CAL2 ((uint16_t*) ((uint32_t) 0x1FFF75CA)) //110摄氏度时的MCU内部温度传感器校准值 #define TS_CAL2 ((uint16_t *) ((uint32_t) 0x1FFF75CA))//110摄氏度时的MCU内部温度传感器校准值
/*滑动平均滤波器长度*/
#define MVF_LENGTH 128
float moving_average_filtre(float xn) {
static int index = -1;
static float buffer[MVF_LENGTH];
static float sum = 0;
float yn = 0;
int i = 0;
if (index == -1) {
//初始化
for (i = 0; i < MVF_LENGTH; i++) {
buffer[i] = xn;
}
sum = xn * MVF_LENGTH;
index = 0;
} else {
sum -= buffer[index];
buffer[index] = xn;
sum += xn;
index++;
if (index >= MVF_LENGTH) {
index = 0;
}
}
yn = sum / MVF_LENGTH;
return yn;
}
//float Current_Temp1, ii=0.0f, iii=0.0f;
//#define PWM_FREQUENCY 24000
//#define CURRENT_MEASURE_HZ PWM_FREQUENCY
//#define CURRENT_MEASURE_PERIOD (float) (1.0f / (float) CURRENT_MEASURE_HZ)
//
//#define TIMER0_CLK_MHz 168
//#define PWM_PERIOD_CYCLES (uint16_t)((TIMER0_CLK_MHz * (uint32_t) 1000000u / ((uint32_t) (PWM_FREQUENCY))) & 0xFFFE)
//#define HALF_PWM_PERIOD_CYCLES (uint16_t)(PWM_PERIOD_CYCLES / 2U)
int ret;
void APP_Main() { void APP_Main() {
// TIM1->CCR1 = 0; // MCT_set_state(CALIBRATION);
// TIM1->CCR2 = 0; printf("%f,%f,%f\n", Foc.i_a, Foc.i_b, Foc.i_c);
// TIM1->CCR3 = 100;
// TIM1->CCR4 = 10;
// ii += 0.000001f; if (USART1_IRQHandler_Status) {
//// if (ii == 0.1f) { ii = 0.1f-0.00001f; } switch (RxBuffer[0]) {
// iii += 0.03f; case 10:
// if (iii >= 360.0f) { iii = 0.0f; } switch (RxBuffer[1]) {
// Current_Temp = ((110.0 - 30) / (*TS_CAL2 - *TS_CAL1) * (int16_t) (adc1_RegularBuf[1] * 3.3 / 3.0 - *TS_CAL1)) + 30; case 10:
// Current_Temp1 = moving_average_filtre(Current_Temp * sinf(ii)); ret = MCT_set_state(IDLE);
// SendCurrent_Vofa(Current_Temp * sinf(ii), Current_Temp1, 0); printf("IDLE ret:%d\r\n", ret);
break;
// Generate(0, 0.02f, iii); }
// SendCurrent_Vofa(FOC.dtc_a, iii,(uint16_t) (FOC.dtc_a * (float) HALF_PWM_PERIOD_CYCLES)); break;
// TIM1->CCR1 = (uint16_t) (FOC.dtc_a * (float) HALF_PWM_PERIOD_CYCLES); case 00:
// TIM1->CCR2 = (uint16_t) (FOC.dtc_b * (float) HALF_PWM_PERIOD_CYCLES); switch (RxBuffer[1]) {
// TIM1->CCR3 = (uint16_t) (FOC.dtc_c * (float) HALF_PWM_PERIOD_CYCLES); case 00:
UsrConfig.control_mode = CONTROL_MODE_TORQUE_RAMP;
// SendCurrent_Vofa(FOC.dtc_a, ii,0); printf("UsrConfig.control_mode->CONTROL_MODE_TORQUE_RAMP\r\n");
break;
// usb_printf("%f\r\n", NowAngle); case 01:
UsrConfig.control_mode = CONTROL_MODE_VELOCITY_RAMP;
printf("UsrConfig.control_mode->CONTROL_MODE_VELOCITY_RAMP\r\n");
// usb_printf("CoreTemp:%d,%d, %.2f\r\n", adc1_RegularBuf[0], adc1_RegularBuf[1], Current_Temp); break;
// usb_printf("PhaseCurrent:%d, %d, %d\r\n", ADC1->JDR1 - 2040, ADC2->JDR1 - 2024, ADC1->JDR2 - 2024); case 02:
// usb_printf("PhaseVoltage:%d, %d, %d\r\n", ADC2->JDR2, ADC2->JDR3, ADC2->JDR4); UsrConfig.control_mode = CONTROL_MODE_POSITION_FILTER;
// SendCurrent_Vofa(FOC.dtc_a, FOC.dtc_b,FOC.dtc_c); printf("UsrConfig.control_mode->CONTROL_MODE_POSITION_FILTER\r\n");
// SendCurrent_Vofa(ADC1->JDR1, FOC.dtc_a, 0 ); break;
case 03:
// CurrA = ia/4096*3.3/0.005f/7.33333; UsrConfig.control_mode = CONTROL_MODE_POSITION_PROFILE;
// SendCurrent_Vofa((ADC1->JDR1)/4096.0f*3.3f/0.005f/7.33333f, ADC2->JDR1, ADC1->JDR2); printf("UsrConfig.control_mode->CONTROL_MODE_POSITION_PROFILE\r\n");
// usb_printf("PhaseVoltage:%d\r\n", (ADC1->JDR1-2048.0f)/4096.0f*3.3f/0.005f/7.33333f); break;
case 04:
// NowAngle = Data.Angle.getAngle(); ret = MCT_set_state(IDLE);
// SendCurrent_Vofa(FOC.dtc_a, NowAngle, 0); printf("IDLE ret:%d\r\n", ret);
// HAL_Delay(10); break;
case 05:
ret = MCT_set_state(CALIBRATION);
printf("CALIBRATION ret:%d\r\n", ret);
break;
case 06:
ret = MCT_set_state(RUN);
printf("RUN ret:%d\r\n", ret);
break;
}
Controller.input_position = (float) ((float) RxBuffer[1] / 10.0f);
Controller.input_velocity = (float) ((float) RxBuffer[1] / 10.0f);
printf("Controller.input_position->%f\r\n", Controller.input_position);
printf("Controller.input_position->%f\r\n", Controller.input_position);
break;
case 01:
Controller.input_position = (float) ((float) RxBuffer[1] / 10.0f);
Controller.input_velocity = (float) ((float) RxBuffer[1] / 10.0f);
printf("Controller.input_position->%f\r\n", Controller.input_position);
printf("Controller.input_position->%f\r\n", Controller.input_position);
break;
case 02:
UsrConfig.pos_gain = (float) ((float) RxBuffer[1]);
printf("UsrConfig.pos_gain->%f\r\n", UsrConfig.pos_gain);
break;
case 03:
UsrConfig.vel_gain = (float) ((float) RxBuffer[1] / 100.0f);
printf("UsrConfig.vel_gain->%f\r\n", UsrConfig.vel_gain);
break;
case 04:
UsrConfig.vel_integrator_gain = (float) ((float) RxBuffer[1] / 1000.0f);
printf("UsrConfig.vel_integrator_gain->%f\r\n", UsrConfig.vel_integrator_gain);
break;
}
USART1_IRQHandler_Status = 0;
}
} }
//软件循环读取ADC
// HAL_ADC_Start(&hadc1);
// if (HAL_OK == HAL_ADC_PollForConversion(&hadc1, 50)) {
// ADC_VAL1 = HAL_ADC_GetValue(&hadc1);
// }

View File

@ -6,36 +6,42 @@
#define BOOOOMFOC_STSPIN32G4_EVB_APP_MAIN_H #define BOOOOMFOC_STSPIN32G4_EVB_APP_MAIN_H
#include "main.h" #include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "adc.h" #include "adc.h"
#include "dma.h" #include "dma.h"
#include "i2c.h" #include "gpio.h"
#include "opamp.h" #include "opamp.h"
#include "spi.h" #include "spi.h"
#include "tim.h" #include "tim.h"
#include "usb_device.h" //#include "arm_math.h"
#include "gpio.h" //#include "Communication.h"
#include "usbd_cdc_if.h"
#include "arm_math.h"
#include "Communication.h"
#include "InteriorADC.h" #include "InteriorADC.h"
#include "Angle.h" #include "Angle.h"
extern tData Data;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;
extern uint8_t RxBuffer[2];//接收数据
extern uint8_t USART1_IRQHandler_Status;
extern volatile uint32_t SystickCount;
// LED ACT
#define LED_ACT_SET()
#define LED_ACT_RESET()
#define LED_ACT_GET()
static inline void watch_dog_feed(void)
{
// FWDGT_CTL = FWDGT_KEY_RELOAD;
}
static inline uint32_t get_ms_since(uint32_t tick)
{
return (uint32_t) ((SystickCount - tick) / 2U);
}
static __IO uint16_t adc1_RegularBuf[10]; static __IO uint16_t adc1_RegularBuf[10];
void APP_Init(); void APP_Init();
void APP_Main(); void APP_Main();
void APP_Task();
#endif //BOOOOMFOC_STSPIN32G4_EVB_APP_MAIN_H #endif//BOOOOMFOC_STSPIN32G4_EVB_APP_MAIN_H

View File

@ -1,75 +1,460 @@
// /*
// Created by ZK on 24-5-10. Copyright 2021 codenocold codenocold@qq.com
// Address : https://github.com/codenocold/dgm
This file is part of the dgm firmware.
The dgm firmware is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The dgm firmware is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "APP_Task.h" //#include "anticogging.h"
#include "calibration.h"
//#include "can.h"
#include "APP_Main.h" #include "APP_Main.h"
#include "Angle.h" #include "APP_Task.h"
#include "InteriorADC.h" #include "anticogging.h"
#include "Controller/Controller.h" #include "controller.h"
#include "Controller/SVPWM/SVPWM.h" #include "encoder.h"
#include "foc.h"
#include "pwm_curr.h"
#include "usr_config.h"
#include "util.h"
#include <math.h>
#include <string.h>
#define UTILS_LP_FAST(value, sample, filter_constant) (value -= (filter_constant) * ((value) - (sample))) typedef struct sFSM {
tFSMState state;
tFSMState state_next;
uint8_t state_next_ready;
} tFSM;
float CurrA, CurrB, CurrC; static volatile tFSM mFSM;
float Current_Temp, V_Temp;
//float32_t NowAngle;
float Current_Temp1, ii = 0.0f, Test_Angle = 0.0f; volatile tMCStatusword StatuswordNew;
volatile tMCStatusword StatuswordOld;
;
#define PWM_FREQUENCY 24000 #define CHARGE_BOOT_CAP_MS 10
#define CURRENT_MEASURE_HZ PWM_FREQUENCY #define CHARGE_BOOT_CAP_TICKS (uint16_t)((PWM_FREQUENCY * CHARGE_BOOT_CAP_MS) / 1000)
#define CURRENT_MEASURE_PERIOD (float) (1.0f / (float) CURRENT_MEASURE_HZ) static uint16_t mChargeBootCapDelay = 0;
#define TIMER0_CLK_MHz 168 static void enter_state(void);
#define PWM_PERIOD_CYCLES (uint16_t)((TIMER0_CLK_MHz * (uint32_t) 1000000u / ((uint32_t) (PWM_FREQUENCY))) & 0xFFFE) static void exit_state(void);
#define HALF_PWM_PERIOD_CYCLES (uint16_t)(PWM_PERIOD_CYCLES / 2U) static void led_act_loop(void);
int up = 1; void MCT_init(void) {
float32_t A, Speedtarget; mFSM.state = BOOT_UP;
int32_t number; mFSM.state_next = BOOT_UP;
int32_t mode = 0; mFSM.state_next_ready = 0;
void High_Frequency_Task() { StatuswordNew.status.status_code = 0;
StatuswordNew.errors.errors_code = 0;
StatuswordOld = StatuswordNew;
}
if (mode < 10000) { void MCT_reset_error(void) {
// HAL_Delay(1000); StatuswordNew.errors.errors_code &= 0x0000FFFF;
mode++; StatuswordOld.errors.errors_code &= 0x0000FFFF;
}
tFSMState MCT_get_state(void) {
return mFSM.state;
}
// return
// 0 Success
// -1 Invalid
// -2 Error code
// -3 Calib invalid
int MCT_set_state(tFSMState state) {
int ret = 0;
switch (mFSM.state) {
case BOOT_UP:
if (state == IDLE) {
mFSM.state_next = IDLE;
} else {
ret = -1;
}
break;
case IDLE:
switch (state) {
case IDLE:
FOC_disarm();
mChargeBootCapDelay = 0;
mFSM.state_next = IDLE;
break;
case RUN:
if (StatuswordNew.errors.errors_code) {
ret = -2;
} else if (!UsrConfig.calib_valid) {
ret = -3;
} else {
FOC_arm();
mChargeBootCapDelay = CHARGE_BOOT_CAP_TICKS;
mFSM.state_next = RUN;
}
break;
case CALIBRATION:
if (StatuswordNew.errors.errors_code) {
ret = -2;
} else {
FOC_arm();
mChargeBootCapDelay = CHARGE_BOOT_CAP_TICKS;
mFSM.state_next = CALIBRATION;
}
break;
case ANTICOGGING:
if (StatuswordNew.errors.errors_code) {
ret = -2;
} else if (!UsrConfig.calib_valid) {
ret = -3;
} else {
FOC_arm();
mChargeBootCapDelay = CHARGE_BOOT_CAP_TICKS;
mFSM.state_next = ANTICOGGING;
}
break;
default:
ret = -1;
break;
}
break;
default:
if (state == IDLE) {
mFSM.state_next = IDLE;
} else {
ret = -1;
}
break;
} }
if (mode >= 10000) {
mFSM.state_next_ready = 0;
number++; return ret;
if (number >= 1 && number <= 10000) { }
Speedtarget = 1.0;
} else if (number >= 10000 && number <= 20000) { static void enter_state(void) {
Speedtarget = -1.0; switch (mFSM.state) {
} else if (number >= 20001) { case BOOT_UP:
number = 0; break;
case IDLE:
break;
case RUN:
CONTROLLER_reset();
StatuswordNew.status.switched_on = 1;
StatuswordNew.status.target_reached = 1;
StatuswordNew.status.current_limit_active = 0;
StatuswordOld.status = StatuswordNew.status;
break;
case CALIBRATION:
CALIBRATION_start();
break;
case ANTICOGGING:
CONTROLLER_reset();
ANTICOGGING_start();
break;
default:
break;
}
}
static void exit_state(void) {
switch (mFSM.state) {
case BOOT_UP:
// CAN_reset_rx_timeout();
// CAN_reset_tx_timeout();
mFSM.state_next_ready = 1;
break;
case IDLE:
if (mChargeBootCapDelay) {
mChargeBootCapDelay--;
} else {
mFSM.state_next_ready = 1;
}
break;
case RUN:
FOC_disarm();
StatuswordNew.status.switched_on = 0;
StatuswordNew.status.target_reached = 0;
StatuswordNew.status.current_limit_active = 0;
StatuswordOld.status = StatuswordNew.status;
mFSM.state_next_ready = 1;
break;
case CALIBRATION:
CALIBRATION_end();
USR_CONFIG_save_config();
printf("UsrConfig.motor_phase_resistance:%f\r\n", UsrConfig.motor_phase_resistance);
printf("UsrConfig.motor_phase_inductance:%f\r\n", UsrConfig.motor_phase_inductance);
printf("UsrConfig.motor_pole_pairs:%ld\r\n", UsrConfig.motor_pole_pairs);
mFSM.state_next_ready = 1;
break;
case ANTICOGGING:
ANTICOGGING_end();
mFSM.state_next_ready = 1;
break;
default:
break;
}
}
int time = 1;
int count = 0;
void MCT_high_frequency_task(void) {
/* state transition management */
if (mFSM.state_next != mFSM.state) {
exit_state();
if (mFSM.state_next_ready) {
mFSM.state = mFSM.state_next;
enter_state();
} }
// Test_Angle += 0.01f; }
// if (Test_Angle > 360.0f) {
// Test_Angle = 0.0f; // if (time >= 0) {
// time++;
// }
//
// if (time == 5) {
// StatuswordNew.errors.errors_code = 0;
// int ret = MCT_set_state(IDLE);
// printf("IDLE ret:%d\r\n", ret);
// }
//
// if (time == 10) {
// int ret = MCT_set_state(CALIBRATION);
// printf("CALIBRATION ret:%d\r\n", ret);
// // UsrConfig.control_mode = CONTROL_MODE_VELOCITY_RAMP;
// // Controller.input_velocity = 0.01f;
//
// time = -1;
// }
// //
// if (UsrConfig.calib_valid && time == -1) {
// int ret = MCT_set_state(RUN);
// printf("RUN ret:%d\r\n", ret);
// UsrConfig.control_mode = CONTROL_MODE_POSITION_PROFILE;
// Controller.input_position = 0.0f;
// Controller.input_velocity = 0.0f;
// time = -2;
// }
//
// if (UsrConfig.calib_valid && time == -2) {
// count++;
// if (count < 50000) {
// Controller.input_position = 5.0f;
// Controller.input_updated = true;
// }
// if (count > 50000) {
// Controller.input_position = 0.5f;
// Controller.input_updated = true;
// }
// if (count > 100000) {
// count = 0;
// }
//
// time = -2;
// } // }
//Data.Angle.getAngle() // ENCODER_loop();
// SendCurrent_Vofa(ADC1->JDR1, ADC2->JDR1, ADC1->JDR2); // FOC_voltage(0,0.001f,Encoder.phase);
// Foc.v_bus = read_vbus();
// float test = 0; Foc.v_bus = 24.0f;
// UTILS_LP_FAST(test, 12, 0.05f); UTILS_LP_FAST(Foc.v_bus_filt, Foc.v_bus, 0.05f);
// usb_printf("%f\r\n", test); Foc.i_a = read_iphase_a();
Foc.i_b = read_iphase_b();
Foc.i_c = read_iphase_c();
// Generate_SVM(0.0f, 0.05f, Data.Angle.getAngle()); switch (mFSM.state) {
// float32_t Eangle = Data.Angle.getAngle(); case BOOT_UP:
SpeedControl(Speedtarget, MT_ReadAngle(),10.0f); break;
FOC_current(0, 10.0f, Data.Angle.getAngle(), 5000);
// SendCurrent_Vofa(Test_Angle,A, (FOC.dtc_a * (float) HALF_PWM_PERIOD_CYCLES)); case CALIBRATION:
CALIBRATION_loop();
break;
case ANTICOGGING:
ANTICOGGING_loop();
// SendCurrent_Vofa((ADC1->JDR1)/4096.0f*3.3f/0.005f/7.33333f, 0, 0); case RUN: {
CONTROLLER_loop();
// check motor current
// If Ia + Ib + Ic == 0 holds then we have: Inorm^2 = Id^2 + Iq^2 = Ialpha^2 + Ibeta^2 = 2/3 * (Ia^2 + Ib^2 + Ic^2)
float Inorm_sq = 2.0f / 3.0f * (SQ(Foc.i_a) + SQ(Foc.i_b) + SQ(Foc.i_c));
if (Inorm_sq > SQ(UsrConfig.protect_over_current)) {
FOC_disarm();
MCT_set_state(IDLE);
StatuswordNew.errors.over_current = 1;
}
// check I bus current
if (Foc.i_bus > UsrConfig.protect_i_bus_max) {
FOC_disarm();
MCT_set_state(IDLE);
StatuswordNew.errors.over_current = 1;
}
} break;
default:
break;
}
}
void MCT_safety_task(void) {
// VBUS check
if (mFSM.state != BOOT_UP) {
// Over voltage check
if (Foc.v_bus > UsrConfig.protect_over_voltage) {
StatuswordNew.errors.over_voltage = 1;
}
// Under voltage check
if (Foc.v_bus < UsrConfig.protect_under_voltage) {
StatuswordNew.errors.under_voltage = 1;
}
// Enchoder state check
if (MT6816.check_err_count > 50 || MT6816.rx_err_count > 50) {
StatuswordNew.errors.encoder_offline = 1;
}
} }
} watch_dog_feed();
}
void MCT_low_priority_task(void) {
bool isSend = false;
// State check
if (StatuswordOld.status.status_code != StatuswordNew.status.status_code) {
isSend = true;
StatuswordOld.status.status_code = StatuswordNew.status.status_code;
}
// Error check
if (StatuswordOld.errors.errors_code != StatuswordNew.errors.errors_code) {
if (StatuswordNew.errors.errors_code) {
FOC_disarm();
MCT_set_state(IDLE);
}
isSend = true;
StatuswordOld.errors.errors_code = StatuswordNew.errors.errors_code;
}
if (isSend) {
CAN_tx_statusword(StatuswordNew);
}
led_act_loop();
CAN_comm_loop();
}
static void led_act_loop(void) {
static uint16_t tick = 0;
static uint32_t tick_100Hz = 0;
// 100Hz
if (get_ms_since(tick_100Hz) < 10) {
return;
}
tick_100Hz = SystickCount;
switch (mFSM.state) {
case IDLE:
if (tick == 0) {
LED_ACT_SET();
} else if (tick == 10) {
LED_ACT_RESET();
} else if (tick > 100) {
tick = 0xFFFF;
}
break;
case RUN:
if (tick == 0) {
LED_ACT_SET();
} else if (tick == 10) {
LED_ACT_RESET();
} else if (tick == 20) {
LED_ACT_SET();
} else if (tick == 30) {
LED_ACT_RESET();
} else if (tick > 100) {
tick = 0xFFFF;
}
break;
case CALIBRATION:
if (tick == 0) {
LED_ACT_SET();
} else if (tick == 10) {
LED_ACT_RESET();
} else if (tick == 20) {
LED_ACT_SET();
} else if (tick == 30) {
LED_ACT_RESET();
} else if (tick == 40) {
LED_ACT_SET();
} else if (tick == 50) {
LED_ACT_RESET();
} else if (tick > 150) {
tick = 0xFFFF;
}
break;
case ANTICOGGING:
if (tick == 0) {
LED_ACT_SET();
} else if (tick == 10) {
LED_ACT_RESET();
} else if (tick == 20) {
LED_ACT_SET();
} else if (tick == 30) {
LED_ACT_RESET();
} else if (tick == 40) {
LED_ACT_SET();
} else if (tick == 50) {
LED_ACT_RESET();
} else if (tick == 60) {
LED_ACT_SET();
} else if (tick == 70) {
LED_ACT_RESET();
} else if (tick > 200) {
tick = 0xFFFF;
}
break;
default:
break;
}
tick++;
}

View File

@ -1,10 +1,57 @@
// #ifndef __MC_TASKS_H__
// Created by ZK on 24-5-10. #define __MC_TASKS_H__
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_APP_TASK_H #include "main.h"
#define BOOOOMFOC_STSPIN32G4_EVB_APP_TASK_H
void High_Frequency_Task(); // Motor controler state
typedef enum eFSMState {
BOOT_UP = 0,
IDLE = 1,
RUN = 2,
CALIBRATION = 3,
ANTICOGGING = 4,
} tFSMState;
#endif //BOOOOMFOC_STSPIN32G4_EVB_APP_TASK_H typedef struct sMCStatusword
{
union {
uint32_t status_code;
struct
{
uint32_t switched_on : 1;
uint32_t target_reached : 1;
uint32_t current_limit_active : 1;
uint32_t PADDING : 29;
};
} status;
union {
uint32_t errors_code;
struct
{
// FATAL
uint32_t adc_selftest_fatal : 1; // 1<<0
uint32_t encoder_offline : 1; // 1<<1
uint32_t PADDING_1 : 14;
// ERROR
uint32_t over_voltage : 1; // 1<<16
uint32_t under_voltage : 1; // 1<<17
uint32_t over_current : 1; // 1<<18
uint32_t PADDING_2 : 13;
};
} errors;
} tMCStatusword;
extern volatile tMCStatusword StatuswordNew;
extern volatile tMCStatusword StatuswordOld;
void MCT_init(void);
void MCT_reset_error(void);
tFSMState MCT_get_state(void);
int MCT_set_state(tFSMState state);
void MCT_high_frequency_task(void);
void MCT_safety_task(void);
void MCT_low_priority_task(void);
#endif

View File

@ -1,27 +1,27 @@
////
//// Created by ZK on 2023/3/14.
////
// //
// Created by ZK on 2023/3/14. //#include "PID.h"
// //
//float PID_Generate(PID *pid) {
#include "PID.h" // pid->error = pid->target - pid->value;
//
float PID_Generate(PID *pid) { // if (pid->error > pid->errMin || pid->error < -pid->errMin)
pid->error = pid->target - pid->value; // pid->errSum += pid->error * pid->ki;
//
if (pid->error > pid->errMin || pid->error < -pid->errMin) // if (pid->errSum > pid->errSumMax)
pid->errSum += pid->error * pid->ki; // pid->errSum = pid->errSumMax;
// else if (pid->errSum < -pid->errSumMax)
if (pid->errSum > pid->errSumMax) // pid->errSum = -pid->errSumMax;
pid->errSum = pid->errSumMax; //
else if (pid->errSum < -pid->errSumMax) // pid->errDt = pid->error - pid->lastErr;
pid->errSum = -pid->errSumMax; // pid->lastErr = pid->error;
//
pid->errDt = pid->error - pid->lastErr; // pid->result = pid->kp * pid->error + pid->errSum + pid->kd * pid->errDt;
pid->lastErr = pid->error; //
// if (pid->result > pid->valMax)
pid->result = pid->kp * pid->error + pid->errSum + pid->kd * pid->errDt; // pid->result = pid->valMax;
// else if (pid->result < -pid->valMax)
if (pid->result > pid->valMax) // pid->result = -pid->valMax;
pid->result = pid->valMax; //}
else if (pid->result < -pid->valMax)
pid->result = -pid->valMax;
}

View File

@ -1,32 +1,32 @@
////
//// Created by ZK on 2023/3/14.
////
// //
// Created by ZK on 2023/3/14. //#ifndef BOOOOMFOC_STSPIN32G4_EVB_PID_H
//#define BOOOOMFOC_STSPIN32G4_EVB_PID_H
// //
//typedef struct pid {
#ifndef BOOOOMFOC_STSPIN32G4_EVB_PID_H // float kp;//比例系数
#define BOOOOMFOC_STSPIN32G4_EVB_PID_H // float ki;//积分系数
// float kd;//微分系数
typedef struct pid { //
float kp;//比例系数 // float target;
float ki;//积分系数 // float value;
float kd;//微分系数 // float error;
//
float target; // float errSum;
float value; // float errSumMax;
float error; //
// float errMin;
float errSum; // float valMax;
float errSumMax; //
// float lastErr;
float errMin; // float errDt;
float valMax; //
// float result;
float lastErr; //} PID;
float errDt; //
//float PID_Generate(PID *pid);
float result; //
} PID; //
//#endif //BOOOOMFOC_STSPIN32G4_EVB_PID_H
float PID_Generate(PID *pid);
#endif //BOOOOMFOC_STSPIN32G4_EVB_PID_H

View File

@ -1,43 +1,43 @@
////
//// Created by ZK on 2023/3/14.
////
// //
// Created by ZK on 2023/3/14. ////#include "Communication.h"
//#include "APP_Main.h"
//
//#define BYTE0(dwTemp) (*(char*)(&dwTemp))
//#define BYTE1(dwTemp) (*((char*)(&dwTemp) + 1))
//#define BYTE2(dwTemp) (*((char*)(&dwTemp) + 2))
//#define BYTE3(dwTemp) (*((char*)(&dwTemp) + 3))
//
//uint8_t USBCDC_SendBuffur[APP_TX_DATA_SIZE];
//
//void SendCurrent_Vofa(float a, float b, float c) {
// uint16_t USBCDC_SendBuffur_count = 0;
// //
//#include "Communication.h"
#include "APP_Main.h"
#define BYTE0(dwTemp) (*(char*)(&dwTemp))
#define BYTE1(dwTemp) (*((char*)(&dwTemp) + 1))
#define BYTE2(dwTemp) (*((char*)(&dwTemp) + 2))
#define BYTE3(dwTemp) (*((char*)(&dwTemp) + 3))
uint8_t USBCDC_SendBuffur[APP_TX_DATA_SIZE];
void SendCurrent_Vofa(float a, float b, float c) {
uint16_t USBCDC_SendBuffur_count = 0;
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(b);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(b);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(b);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(b);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(c);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(c);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(c);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(c);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(a); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(a);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(a); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(a);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(a);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(a);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(b); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(b);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(b); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(b);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(b);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(b);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(c); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(c);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(c); // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(c);
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE2(c);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x00; // USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE3(c);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x00; //// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x80; //// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(a);
USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x7f; //// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(b);
//// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(b);
CDC_Transmit_FS(USBCDC_SendBuffur, USBCDC_SendBuffur_count); //// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE0(c);
} //// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = BYTE1(c);
//
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x00;
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x00;
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x80;
// USBCDC_SendBuffur[USBCDC_SendBuffur_count++] = 0x7f;
//
// CDC_Transmit_FS(USBCDC_SendBuffur, USBCDC_SendBuffur_count);
//}

View File

@ -1,12 +1,12 @@
////
//// Created by ZK on 2023/3/14.
////
// //
// Created by ZK on 2023/3/14. //#ifndef BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H
//#define BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H
// //
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H //void SendCurrent_Vofa(float a, float b, float c);
#define BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H //
//
//#endif //BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H
void SendCurrent_Vofa(float a, float b, float c);
#endif //BOOOOMFOC_STSPIN32G4_EVB_COMMUNICATION_H

View File

@ -1,239 +1,239 @@
////
//// Created by ZK on 2023/3/14.
////
////#include "main.h"
//#include <stdbool.h>
//#include "Controller.h"
//#include "SVPWM/SVPWM.h"
//#include "Communication.h"
//#include "Angle.h"
// //
// Created by ZK on 2023/3/14. //#define UTILS_LP_FAST(value, sample, filter_constant) (value -= (filter_constant) * ((value) - (sample)))
//
//
//tFOC FOC;
//
//float uAlpha1;
//float uBeta1;
//
//#define PWM_FREQUENCY 24000
//#define CURRENT_MEASURE_HZ PWM_FREQUENCY
//#define CURRENT_MEASURE_PERIOD (float) (1.0f / (float) CURRENT_MEASURE_HZ)
//
//#define TIMER0_CLK_MHz 168
//#define PWM_PERIOD_CYCLES (uint16_t)((TIMER0_CLK_MHz * (uint32_t) 1000000u / ((uint32_t) (PWM_FREQUENCY))) & 0xFFFE)
//#define HALF_PWM_PERIOD_CYCLES (uint16_t)(PWM_PERIOD_CYCLES / 2U)
//float current1, current2, current3;
//
//float32_t id_curr_pi_kp = 0.001f;
//float32_t id_curr_pi_ki = 0.000001f;
//
//float32_t id_curr_pi_target = 0.0f;
//float32_t id_curr_pi_value;
//float32_t id_curr_pi_error;
//
//float32_t id_curr_pi_errMin = 0.0f;
//float32_t id_curr_pi_errSum;
//float32_t id_curr_pi_errSumMax = 30.0f;
//
//float32_t id_curr_pi_result;
//
//
//float32_t iq_curr_pi_kp = 0.001f;
//float32_t iq_curr_pi_ki = 0.000001f;
//
//float32_t iq_curr_pi_target = 1.0f;
//float32_t iq_curr_pi_value;
//float32_t iq_curr_pi_error;
//
//float32_t iq_curr_pi_errMin = 0.0f;
//float32_t iq_curr_pi_errSum;
//float32_t iq_curr_pi_errSumMax = 30.0f;
//
//float32_t iq_curr_pi_result;
//
//
//float32_t Speed_target = 0.0f;
//
//float32_t Speedpid_error;
//float32_t Speedpid_errSum;
//float32_t Speedpid_kp = 1.0f;
//float32_t Speedpid_ki = 0.1f;
//float32_t Speedpid_kd = 1.0f;
//float32_t Speedpid_errSumMax = 30.0f;
//float32_t Speedpid_lastErr;
//float32_t Speedpid_errDt;
//float32_t Speedpid_result;
//
//
//float32_t u_d, u_q;
//
//
//static void Current_PI_Cal_Id(float32_t resultMax) {
// //curr_pi_target = target;
//
// id_curr_pi_error = id_curr_pi_target - id_curr_pi_value;
//
//// if(curr_pi_error > PI_Control->errMin || curr_pi_error < -PI_Control->errMin)
// id_curr_pi_errSum += id_curr_pi_error * id_curr_pi_ki;
//
// if (id_curr_pi_errSum > id_curr_pi_errSumMax)
// id_curr_pi_errSum = id_curr_pi_errSumMax;
// else if (id_curr_pi_errSum < -id_curr_pi_errSumMax)
// id_curr_pi_errSum = -id_curr_pi_errSumMax;
//
// id_curr_pi_result = id_curr_pi_kp * id_curr_pi_error + id_curr_pi_errSum;
//
// if (id_curr_pi_result > resultMax)
// id_curr_pi_result = resultMax;
// else if (id_curr_pi_result < -resultMax)
// id_curr_pi_result = -resultMax;
//}
//
//
//static void Current_PI_Cal_Iq(float32_t resultMax) {
// //curr_pi_target = target;
//
// iq_curr_pi_error = iq_curr_pi_target - iq_curr_pi_value;
//
//// if(curr_pi_error > PI_Control->errMin || curr_pi_error < -PI_Control->errMin)
// iq_curr_pi_errSum += iq_curr_pi_error * iq_curr_pi_ki;
//
// if (iq_curr_pi_errSum > iq_curr_pi_errSumMax)
// iq_curr_pi_errSum = iq_curr_pi_errSumMax;
// else if (iq_curr_pi_errSum < -iq_curr_pi_errSumMax)
// iq_curr_pi_errSum = -iq_curr_pi_errSumMax;
//
// iq_curr_pi_result = iq_curr_pi_kp * iq_curr_pi_error + iq_curr_pi_errSum;
//
// if (iq_curr_pi_result > resultMax)
// iq_curr_pi_result = resultMax;
// else if (iq_curr_pi_result < -resultMax)
// iq_curr_pi_result = -resultMax;
//}
//
//
//static float32_t PIDGetResult(float32_t Speedpid_value, float32_t valMax, float32_t errMin) {
// Speedpid_error = Speed_target - Speedpid_value;
//
// if (Speedpid_error > errMin || Speedpid_error < -errMin)
// Speedpid_errSum += Speedpid_error * Speedpid_ki;
//
// if (Speedpid_errSum > Speedpid_errSumMax)
// Speedpid_errSum = Speedpid_errSumMax;
// else if (Speedpid_errSum < -Speedpid_errSumMax)
// Speedpid_errSum = -Speedpid_errSumMax;
//
// Speedpid_errDt = Speedpid_error - Speedpid_lastErr;
// Speedpid_lastErr = Speedpid_error;
//
// Speedpid_result = Speedpid_kp * Speedpid_error + Speedpid_errSum + Speedpid_kd * Speedpid_errDt;
//
// if (Speedpid_result > valMax)
// Speedpid_result = valMax;
// else if (Speedpid_result < -valMax)
// Speedpid_result = -valMax;
//
// return Speedpid_result;
//}
//
//
//void SpeedControl(float32_t target, float32_t angleVal, float32_t valMax) {
// Speed_target = target;
// float32_t motorControl_speedValue = GetSpeed(angleVal);
//// SendCurrent_Vofa(motorControl_speedValue, target, 0);
//// speedPID_value = motorControl_speedValue;
//
// iq_curr_pi_target = PIDGetResult(motorControl_speedValue, valMax, 0.0f);
//}
//
//
//
//
////bool Generate_SVM(float ud, float uq, float Theta) {
//bool FOC_current(float Id_set, float Iq_set, float Theta, float bw) {
// if (id_curr_pi_target > Id_set) { id_curr_pi_target = Id_set; }
// if (iq_curr_pi_target > Iq_set) { iq_curr_pi_target = Iq_set; }
//// id_curr_pi_target = Id_set;
//// iq_curr_pi_target = Iq_set;
//
// current1 = ADC1->JDR2;
// current2 = ADC2->JDR1;
// current3 = ADC1->JDR1;
// current1 = (current1 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f) + 0.23;
// current2 = (current2 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f);
// current3 = (current3 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f) - 0.4;
//// SendCurrent_Vofa(current1, current2, current3);
//
// // Clarke transform
// float i_alpha, i_beta;
// clarke_transform(current1, current2, current3, &i_alpha, &i_beta);
// // Park transform
// float i_d, i_q;
// park_transform(i_alpha, i_beta, Theta, &i_d, &i_q);
//
// id_curr_pi_value = i_d;
// iq_curr_pi_value = i_q;
// Current_PI_Cal_Id(1.0f);
// Current_PI_Cal_Iq(1.0f);
// u_d = id_curr_pi_result;
// u_q = iq_curr_pi_result;
//
//
// // float mod_to_V = FOC.v_bus_filt * 2.0f / 3.0f;
// // float V_to_mod = 1.0f / mod_to_V;
// float mod_to_V = 1.2f * 2.0f / 3.0f;
// float V_to_mod = 1.0f / mod_to_V;
//
// float bandwidth = MIN(bw, 0.25f * PWM_FREQUENCY);
// // Apply PI control
// float Ierr_d = Id_set - i_d;
// float Ierr_q = Iq_set - i_q;
//// FOC.current_ctrl_p_gain = 5.0f * bandwidth;
//// FOC.current_ctrl_i_gain = 0.000002f * bandwidth;
// FOC.current_ctrl_p_gain = 0.001f;
// FOC.current_ctrl_i_gain = 0.00001f;
// FOC.current_ctrl_integral_d = 0;
// FOC.current_ctrl_integral_q = 0;
// float mod_d = V_to_mod * (FOC.current_ctrl_integral_d + Ierr_d * FOC.current_ctrl_p_gain);
// float mod_q = V_to_mod * (FOC.current_ctrl_integral_q + Ierr_q * FOC.current_ctrl_p_gain);
//
// // Vector modulation saturation, lock integrator if saturated
// float mod_scalefactor = 0.9f * SQRT3_BY_2 / sqrtf(SQ(mod_d) + SQ(mod_q));
// if (mod_scalefactor < 1.0f) {
// mod_d *= mod_scalefactor;
// mod_q *= mod_scalefactor;
// FOC.current_ctrl_integral_d *= 0.99f;
// FOC.current_ctrl_integral_q *= 0.99f;
// } else {
// FOC.current_ctrl_integral_d += Ierr_d * (FOC.current_ctrl_i_gain * CURRENT_MEASURE_PERIOD);
// FOC.current_ctrl_integral_q += Ierr_q * (FOC.current_ctrl_i_gain * CURRENT_MEASURE_PERIOD);
// }
//
//
// float pwm_phase = Theta + Theta * M_2PI * 20 * CURRENT_MEASURE_PERIOD;
// inversePark(u_d, u_q, Theta, &uAlpha1, &uBeta1);
//
// FOC.i_q = i_q;
// UTILS_LP_FAST(FOC.i_q_filt, FOC.i_q, 0.01f);
// FOC.i_d = i_d;
// UTILS_LP_FAST(FOC.i_d_filt, FOC.i_d, 0.01f);
// FOC.i_bus = (mod_d * i_d + mod_q * i_q);
// UTILS_LP_FAST(FOC.i_bus_filt, FOC.i_bus, 0.01f);
// FOC.power_filt = FOC.v_bus_filt * FOC.i_bus_filt;
//
// SVPWM(uAlpha1, uBeta1, &FOC.dtc_a, &FOC.dtc_b, &FOC.dtc_c);
//// FOC.dtc_a = FOC.dtc_a * 0.01;
//// FOC.dtc_b = FOC.dtc_b * 0.01;
//// FOC.dtc_c = FOC.dtc_c * 0.01;
// SendCurrent_Vofa(mod_d, mod_q, iq_curr_pi_target);
// TIM1->CCR1 = (uint16_t) (FOC.dtc_c * (float) HALF_PWM_PERIOD_CYCLES);
// TIM1->CCR2 = (uint16_t) (FOC.dtc_b * (float) HALF_PWM_PERIOD_CYCLES);
// TIM1->CCR3 = (uint16_t) (FOC.dtc_a * (float) HALF_PWM_PERIOD_CYCLES);
//// TIM1->CCR1 = (uint16_t) FOC.dtc_a;
//// TIM1->CCR2 = (uint16_t) FOC.dtc_b;
//// TIM1->CCR3 = (uint16_t) FOC.dtc_c;
//
// return 0;
//}
// //
//#include "main.h"
#include <stdbool.h>
#include "Controller.h"
#include "SVPWM/SVPWM.h"
#include "Communication.h"
#include "Angle.h"
#define UTILS_LP_FAST(value, sample, filter_constant) (value -= (filter_constant) * ((value) - (sample)))
tFOC FOC;
float uAlpha1;
float uBeta1;
#define PWM_FREQUENCY 24000
#define CURRENT_MEASURE_HZ PWM_FREQUENCY
#define CURRENT_MEASURE_PERIOD (float) (1.0f / (float) CURRENT_MEASURE_HZ)
#define TIMER0_CLK_MHz 168
#define PWM_PERIOD_CYCLES (uint16_t)((TIMER0_CLK_MHz * (uint32_t) 1000000u / ((uint32_t) (PWM_FREQUENCY))) & 0xFFFE)
#define HALF_PWM_PERIOD_CYCLES (uint16_t)(PWM_PERIOD_CYCLES / 2U)
float current1, current2, current3;
float32_t id_curr_pi_kp = 0.001f;
float32_t id_curr_pi_ki = 0.000001f;
float32_t id_curr_pi_target = 0.0f;
float32_t id_curr_pi_value;
float32_t id_curr_pi_error;
float32_t id_curr_pi_errMin = 0.0f;
float32_t id_curr_pi_errSum;
float32_t id_curr_pi_errSumMax = 30.0f;
float32_t id_curr_pi_result;
float32_t iq_curr_pi_kp = 0.001f;
float32_t iq_curr_pi_ki = 0.000001f;
float32_t iq_curr_pi_target = 1.0f;
float32_t iq_curr_pi_value;
float32_t iq_curr_pi_error;
float32_t iq_curr_pi_errMin = 0.0f;
float32_t iq_curr_pi_errSum;
float32_t iq_curr_pi_errSumMax = 30.0f;
float32_t iq_curr_pi_result;
float32_t Speed_target = 0.0f;
float32_t Speedpid_error;
float32_t Speedpid_errSum;
float32_t Speedpid_kp = 1.0f;
float32_t Speedpid_ki = 0.1f;
float32_t Speedpid_kd = 1.0f;
float32_t Speedpid_errSumMax = 30.0f;
float32_t Speedpid_lastErr;
float32_t Speedpid_errDt;
float32_t Speedpid_result;
float32_t u_d, u_q;
static void Current_PI_Cal_Id(float32_t resultMax) {
//curr_pi_target = target;
id_curr_pi_error = id_curr_pi_target - id_curr_pi_value;
// if(curr_pi_error > PI_Control->errMin || curr_pi_error < -PI_Control->errMin)
id_curr_pi_errSum += id_curr_pi_error * id_curr_pi_ki;
if (id_curr_pi_errSum > id_curr_pi_errSumMax)
id_curr_pi_errSum = id_curr_pi_errSumMax;
else if (id_curr_pi_errSum < -id_curr_pi_errSumMax)
id_curr_pi_errSum = -id_curr_pi_errSumMax;
id_curr_pi_result = id_curr_pi_kp * id_curr_pi_error + id_curr_pi_errSum;
if (id_curr_pi_result > resultMax)
id_curr_pi_result = resultMax;
else if (id_curr_pi_result < -resultMax)
id_curr_pi_result = -resultMax;
}
static void Current_PI_Cal_Iq(float32_t resultMax) {
//curr_pi_target = target;
iq_curr_pi_error = iq_curr_pi_target - iq_curr_pi_value;
// if(curr_pi_error > PI_Control->errMin || curr_pi_error < -PI_Control->errMin)
iq_curr_pi_errSum += iq_curr_pi_error * iq_curr_pi_ki;
if (iq_curr_pi_errSum > iq_curr_pi_errSumMax)
iq_curr_pi_errSum = iq_curr_pi_errSumMax;
else if (iq_curr_pi_errSum < -iq_curr_pi_errSumMax)
iq_curr_pi_errSum = -iq_curr_pi_errSumMax;
iq_curr_pi_result = iq_curr_pi_kp * iq_curr_pi_error + iq_curr_pi_errSum;
if (iq_curr_pi_result > resultMax)
iq_curr_pi_result = resultMax;
else if (iq_curr_pi_result < -resultMax)
iq_curr_pi_result = -resultMax;
}
static float32_t PIDGetResult(float32_t Speedpid_value, float32_t valMax, float32_t errMin) {
Speedpid_error = Speed_target - Speedpid_value;
if (Speedpid_error > errMin || Speedpid_error < -errMin)
Speedpid_errSum += Speedpid_error * Speedpid_ki;
if (Speedpid_errSum > Speedpid_errSumMax)
Speedpid_errSum = Speedpid_errSumMax;
else if (Speedpid_errSum < -Speedpid_errSumMax)
Speedpid_errSum = -Speedpid_errSumMax;
Speedpid_errDt = Speedpid_error - Speedpid_lastErr;
Speedpid_lastErr = Speedpid_error;
Speedpid_result = Speedpid_kp * Speedpid_error + Speedpid_errSum + Speedpid_kd * Speedpid_errDt;
if (Speedpid_result > valMax)
Speedpid_result = valMax;
else if (Speedpid_result < -valMax)
Speedpid_result = -valMax;
return Speedpid_result;
}
void SpeedControl(float32_t target, float32_t angleVal, float32_t valMax) {
Speed_target = target;
float32_t motorControl_speedValue = GetSpeed(angleVal);
// SendCurrent_Vofa(motorControl_speedValue, target, 0);
// speedPID_value = motorControl_speedValue;
iq_curr_pi_target = PIDGetResult(motorControl_speedValue, valMax, 0.0f);
}
//bool Generate_SVM(float ud, float uq, float Theta) {
bool FOC_current(float Id_set, float Iq_set, float Theta, float bw) {
if (id_curr_pi_target > Id_set) { id_curr_pi_target = Id_set; }
if (iq_curr_pi_target > Iq_set) { iq_curr_pi_target = Iq_set; }
// id_curr_pi_target = Id_set;
// iq_curr_pi_target = Iq_set;
current1 = ADC1->JDR2;
current2 = ADC2->JDR1;
current3 = ADC1->JDR1;
current1 = (current1 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f) + 0.23;
current2 = (current2 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f);
current3 = (current3 - 2048) * ((3.3f / 4095.0f) / 0.005f / 7.333333f) - 0.4;
// SendCurrent_Vofa(current1, current2, current3);
// Clarke transform
float i_alpha, i_beta;
clarke_transform(current1, current2, current3, &i_alpha, &i_beta);
// Park transform
float i_d, i_q;
park_transform(i_alpha, i_beta, Theta, &i_d, &i_q);
id_curr_pi_value = i_d;
iq_curr_pi_value = i_q;
Current_PI_Cal_Id(1.0f);
Current_PI_Cal_Iq(1.0f);
u_d = id_curr_pi_result;
u_q = iq_curr_pi_result;
// float mod_to_V = FOC.v_bus_filt * 2.0f / 3.0f;
// float V_to_mod = 1.0f / mod_to_V;
float mod_to_V = 1.2f * 2.0f / 3.0f;
float V_to_mod = 1.0f / mod_to_V;
float bandwidth = MIN(bw, 0.25f * PWM_FREQUENCY);
// Apply PI control
float Ierr_d = Id_set - i_d;
float Ierr_q = Iq_set - i_q;
// FOC.current_ctrl_p_gain = 5.0f * bandwidth;
// FOC.current_ctrl_i_gain = 0.000002f * bandwidth;
FOC.current_ctrl_p_gain = 0.001f;
FOC.current_ctrl_i_gain = 0.00001f;
FOC.current_ctrl_integral_d = 0;
FOC.current_ctrl_integral_q = 0;
float mod_d = V_to_mod * (FOC.current_ctrl_integral_d + Ierr_d * FOC.current_ctrl_p_gain);
float mod_q = V_to_mod * (FOC.current_ctrl_integral_q + Ierr_q * FOC.current_ctrl_p_gain);
// Vector modulation saturation, lock integrator if saturated
float mod_scalefactor = 0.9f * SQRT3_BY_2 / sqrtf(SQ(mod_d) + SQ(mod_q));
if (mod_scalefactor < 1.0f) {
mod_d *= mod_scalefactor;
mod_q *= mod_scalefactor;
FOC.current_ctrl_integral_d *= 0.99f;
FOC.current_ctrl_integral_q *= 0.99f;
} else {
FOC.current_ctrl_integral_d += Ierr_d * (FOC.current_ctrl_i_gain * CURRENT_MEASURE_PERIOD);
FOC.current_ctrl_integral_q += Ierr_q * (FOC.current_ctrl_i_gain * CURRENT_MEASURE_PERIOD);
}
float pwm_phase = Theta + Theta * M_2PI * 20 * CURRENT_MEASURE_PERIOD;
inversePark(u_d, u_q, Theta, &uAlpha1, &uBeta1);
FOC.i_q = i_q;
UTILS_LP_FAST(FOC.i_q_filt, FOC.i_q, 0.01f);
FOC.i_d = i_d;
UTILS_LP_FAST(FOC.i_d_filt, FOC.i_d, 0.01f);
FOC.i_bus = (mod_d * i_d + mod_q * i_q);
UTILS_LP_FAST(FOC.i_bus_filt, FOC.i_bus, 0.01f);
FOC.power_filt = FOC.v_bus_filt * FOC.i_bus_filt;
SVPWM(uAlpha1, uBeta1, &FOC.dtc_a, &FOC.dtc_b, &FOC.dtc_c);
// FOC.dtc_a = FOC.dtc_a * 0.01;
// FOC.dtc_b = FOC.dtc_b * 0.01;
// FOC.dtc_c = FOC.dtc_c * 0.01;
SendCurrent_Vofa(mod_d, mod_q, iq_curr_pi_target);
TIM1->CCR1 = (uint16_t) (FOC.dtc_c * (float) HALF_PWM_PERIOD_CYCLES);
TIM1->CCR2 = (uint16_t) (FOC.dtc_b * (float) HALF_PWM_PERIOD_CYCLES);
TIM1->CCR3 = (uint16_t) (FOC.dtc_a * (float) HALF_PWM_PERIOD_CYCLES);
// TIM1->CCR1 = (uint16_t) FOC.dtc_a;
// TIM1->CCR2 = (uint16_t) FOC.dtc_b;
// TIM1->CCR3 = (uint16_t) FOC.dtc_c;
return 0;
}

View File

@ -1,30 +1,30 @@
////
//// Created by ZK on 2023/3/14.
////
// //
// Created by ZK on 2023/3/14. //#ifndef BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H
//#define BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H
// //
//#include "arm_math.h"
#ifndef BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H //
#define BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H //typedef struct sFOC {
// bool is_armed;
#include "arm_math.h" //
// float v_bus, v_bus_filt, i_a, i_b, i_c;
typedef struct sFOC { //
bool is_armed; // float i_q, i_q_filt, i_d, i_d_filt, i_bus, i_bus_filt, power_filt;
// float dtc_a, dtc_b, dtc_c;
float v_bus, v_bus_filt, i_a, i_b, i_c; //
// float current_ctrl_p_gain, current_ctrl_i_gain;
float i_q, i_q_filt, i_d, i_d_filt, i_bus, i_bus_filt, power_filt; // float current_ctrl_integral_d, current_ctrl_integral_q;
float dtc_a, dtc_b, dtc_c; //} tFOC;
//
float current_ctrl_p_gain, current_ctrl_i_gain; //extern tFOC FOC;
float current_ctrl_integral_d, current_ctrl_integral_q; //
} tFOC; //
//extern void SpeedControl(float32_t target, float32_t angleVal, float32_t valMax);
extern tFOC FOC; //
//extern bool FOC_current(float Id_set, float Iq_set, float Theta, float bw);
//
extern void SpeedControl(float32_t target, float32_t angleVal, float32_t valMax); //
//#endif //BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H
extern bool FOC_current(float Id_set, float Iq_set, float Theta, float bw);
#endif //BOOOOMFOC_STSPIN32G4_EVB_CONTROLLER_H

View File

@ -1,22 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "PreDrive.h"
uint8_t PreDrive_Init_Buffur[2] = {0x00, 0x00};
bool PreDrive_Init(void) {
while (HAL_I2C_Mem_Write(&hi2c3, 0x8e, 0x0c, I2C_MEMADD_SIZE_8BIT, PreDrive_Init_Buffur, 1, 1000) != HAL_OK) {}
PreDrive_Init_Buffur[0] = 0x00;
while (HAL_I2C_Mem_Write(&hi2c3, 0x8e, 0x0c, I2C_MEMADD_SIZE_8BIT, PreDrive_Init_Buffur, 1, 1000) != HAL_OK) {}
PreDrive_Init_Buffur[0] = 0xff;
while (HAL_I2C_Mem_Write(&hi2c3, 0x8e, 0x09, I2C_MEMADD_SIZE_8BIT, PreDrive_Init_Buffur, 1, 1000) != HAL_OK) {}
PreDrive_Init_Buffur[0] = 0x00;
while (HAL_I2C_Mem_Write(&hi2c3, 0x8e, 0x09, I2C_MEMADD_SIZE_8BIT, PreDrive_Init_Buffur, 1, 1000) != HAL_OK) {}
HAL_Delay(10);
return 0;
}

View File

@ -1,13 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_PREDRIVE_H
#define BOOOOMFOC_STSPIN32G4_EVB_PREDRIVE_H
#include "APP_Main.h"
bool PreDrive_Init(void);
#endif //BOOOOMFOC_STSPIN32G4_EVB_PREDRIVE_H

View File

@ -1,170 +1,170 @@
////
//// Created by ZK on 2023/3/16.
////
// //
// Created by ZK on 2023/3/16. //#include "SVPWM.h"
// //
//
#include "SVPWM.h" //#define SVM 1
//
//extern uint16_t cycleNum;
#define SVM 1 //
//#define SQRT3 1.732050808f
extern uint16_t cycleNum; //#define LIMIT (float32_t)(0.9f / SQRT3)
//#define LIMIT_UDC 16.0f
#define SQRT3 1.732050808f //#define TS 3300
#define LIMIT (float32_t)(0.9f / SQRT3) //#define SQRT3_MULT_TS (float32_t)((float32_t)TS * SQRT3)
#define LIMIT_UDC 16.0f //
#define TS 3300 //uint8_t sectionMap[7] = {0, 2, 6, 1, 4, 3, 5};
#define SQRT3_MULT_TS (float32_t)((float32_t)TS * SQRT3) //float32_t uAlpha, uBeta;
//float32_t ud, uq;
uint8_t sectionMap[7] = {0, 2, 6, 1, 4, 3, 5}; //float channel1, channel2, channel3, udc = 12;
float32_t uAlpha, uBeta; //float uAlpha, uBeta;
float32_t ud, uq; //float32_t iAlpha, iBeta;
float channel1, channel2, channel3, udc = 12; //float32_t id, iq;
float uAlpha, uBeta; //
float32_t iAlpha, iBeta; //
float32_t id, iq; //inline void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta) {
// *Ialpha = Ia;
// *Ibeta = (Ib - Ic) * ONE_BY_SQRT3;
inline void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta) { //}
*Ialpha = Ia; //
*Ibeta = (Ib - Ic) * ONE_BY_SQRT3; //inline void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq) {
} // float s = sinf(Theta / 57.29577951326093f);
// float c = cosf(Theta / 57.29577951326093f);
inline void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq) { // *Id = Ialpha * c + Ibeta * s;
float s = sinf(Theta / 57.29577951326093f); // *Iq = -Ialpha * s + Ibeta * c;
float c = cosf(Theta / 57.29577951326093f); //}
*Id = Ialpha * c + Ibeta * s; //
*Iq = -Ialpha * s + Ibeta * c; //
} //inline void inversePark(float ud, float uq, float Theta, float *uAlpha, float *uBeta) {
// float s = sinf(Theta / 57.29577951326093f);
// float c = cosf(Theta / 57.29577951326093f);
inline void inversePark(float ud, float uq, float Theta, float *uAlpha, float *uBeta) { // *uAlpha = ud * c - uq * s;
float s = sinf(Theta / 57.29577951326093f); // *uBeta = ud * s + uq * c;
float c = cosf(Theta / 57.29577951326093f); //}
*uAlpha = ud * c - uq * s; //
*uBeta = ud * s + uq * c; //
} //inline int SVPWM(float uAlpha, float uBeta, float *tA, float *tB, float *tC) {
// int Sextant;
//
inline int SVPWM(float uAlpha, float uBeta, float *tA, float *tB, float *tC) { // if (uBeta >= 0.0f) {
int Sextant; // if (uAlpha >= 0.0f) {
// //quadrant I
if (uBeta >= 0.0f) { // if (ONE_BY_SQRT3 * uBeta > uAlpha)
if (uAlpha >= 0.0f) { // Sextant = 2; //sextant v2-v3
//quadrant I // else
if (ONE_BY_SQRT3 * uBeta > uAlpha) // Sextant = 1; //sextant v1-v2
Sextant = 2; //sextant v2-v3 //
else // } else {
Sextant = 1; //sextant v1-v2 // //quadrant II
// if (-ONE_BY_SQRT3 * uBeta > uAlpha)
} else { // Sextant = 3; //sextant v3-v4
//quadrant II // else
if (-ONE_BY_SQRT3 * uBeta > uAlpha) // Sextant = 2; //sextant v2-v3
Sextant = 3; //sextant v3-v4 // }
else // } else {
Sextant = 2; //sextant v2-v3 // if (uAlpha >= 0.0f) {
} // //quadrant IV
} else { // if (-ONE_BY_SQRT3 * uBeta > uAlpha)
if (uAlpha >= 0.0f) { // Sextant = 5; //sextant v5-v6
//quadrant IV // else
if (-ONE_BY_SQRT3 * uBeta > uAlpha) // Sextant = 6; //sextant v6-v1
Sextant = 5; //sextant v5-v6 // } else {
else // //quadrant III
Sextant = 6; //sextant v6-v1 // if (ONE_BY_SQRT3 * uBeta > uAlpha)
} else { // Sextant = 4; //sextant v4-v5
//quadrant III // else
if (ONE_BY_SQRT3 * uBeta > uAlpha) // Sextant = 5; //sextant v5-v6
Sextant = 4; //sextant v4-v5 // }
else // }
Sextant = 5; //sextant v5-v6 //
} // switch (Sextant) {
} // // sextant v1-v2
// case 1: {
switch (Sextant) { // // Vector on-times
// sextant v1-v2 // float t1 = uAlpha - ONE_BY_SQRT3 * uBeta;
case 1: { // float t2 = TWO_BY_SQRT3 * uBeta;
// Vector on-times //
float t1 = uAlpha - ONE_BY_SQRT3 * uBeta; // // PWM timings
float t2 = TWO_BY_SQRT3 * uBeta; // *tA = (1.0f - t1 - t2) * 0.5f;
// *tB = *tA + t1;
// PWM timings // *tC = *tB + t2;
*tA = (1.0f - t1 - t2) * 0.5f; // }
*tB = *tA + t1; // break;
*tC = *tB + t2; //
} // // sextant v2-v3
break; // case 2: {
// // Vector on-times
// sextant v2-v3 // float t2 = uAlpha + ONE_BY_SQRT3 * uBeta;
case 2: { // float t3 = -uAlpha + ONE_BY_SQRT3 * uBeta;
// Vector on-times //
float t2 = uAlpha + ONE_BY_SQRT3 * uBeta; // // PWM timings
float t3 = -uAlpha + ONE_BY_SQRT3 * uBeta; // *tB = (1.0f - t2 - t3) * 0.5f;
// *tA = *tB + t3;
// PWM timings // *tC = *tA + t2;
*tB = (1.0f - t2 - t3) * 0.5f; // }
*tA = *tB + t3; // break;
*tC = *tA + t2; //
} // // sextant v3-v4
break; // case 3: {
// // Vector on-times
// sextant v3-v4 // float t3 = TWO_BY_SQRT3 * uBeta;
case 3: { // float t4 = -uAlpha - ONE_BY_SQRT3 * uBeta;
// Vector on-times //
float t3 = TWO_BY_SQRT3 * uBeta; // // PWM timings
float t4 = -uAlpha - ONE_BY_SQRT3 * uBeta; // *tB = (1.0f - t3 - t4) * 0.5f;
// *tC = *tB + t3;
// PWM timings // *tA = *tC + t4;
*tB = (1.0f - t3 - t4) * 0.5f; // }
*tC = *tB + t3; // break;
*tA = *tC + t4; //
} // // sextant v4-v5
break; // case 4: {
// // Vector on-times
// sextant v4-v5 // float t4 = -uAlpha + ONE_BY_SQRT3 * uBeta;
case 4: { // float t5 = -TWO_BY_SQRT3 * uBeta;
// Vector on-times //
float t4 = -uAlpha + ONE_BY_SQRT3 * uBeta; // // PWM timings
float t5 = -TWO_BY_SQRT3 * uBeta; // *tC = (1.0f - t4 - t5) * 0.5f;
// *tB = *tC + t5;
// PWM timings // *tA = *tB + t4;
*tC = (1.0f - t4 - t5) * 0.5f; // }
*tB = *tC + t5; // break;
*tA = *tB + t4; //
} // // sextant v5-v6
break; // case 5: {
// // Vector on-times
// sextant v5-v6 // float t5 = -uAlpha - ONE_BY_SQRT3 * uBeta;
case 5: { // float t6 = uAlpha - ONE_BY_SQRT3 * uBeta;
// Vector on-times //
float t5 = -uAlpha - ONE_BY_SQRT3 * uBeta; // // PWM timings
float t6 = uAlpha - ONE_BY_SQRT3 * uBeta; // *tC = (1.0f - t5 - t6) * 0.5f;
// *tA = *tC + t5;
// PWM timings // *tB = *tA + t6;
*tC = (1.0f - t5 - t6) * 0.5f; // }
*tA = *tC + t5; // break;
*tB = *tA + t6; //
} // // sextant v6-v1
break; // case 6: {
// // Vector on-times
// sextant v6-v1 // float t6 = -TWO_BY_SQRT3 * uBeta;
case 6: { // float t1 = uAlpha + ONE_BY_SQRT3 * uBeta;
// Vector on-times //
float t6 = -TWO_BY_SQRT3 * uBeta; // // PWM timings
float t1 = uAlpha + ONE_BY_SQRT3 * uBeta; // *tA = (1.0f - t6 - t1) * 0.5f;
// *tC = *tA + t1;
// PWM timings // *tB = *tC + t6;
*tA = (1.0f - t6 - t1) * 0.5f; // }
*tC = *tA + t1; // break;
*tB = *tC + t6; // }
} //
break; // // if any of the results becomes NaN, result_valid will evaluate to false
} // int result_valid = *tA >= 0.0f && *tA <= 1.0f && *tB >= 0.0f && *tB <= 1.0f && *tC >= 0.0f && *tC <= 1.0f;
//
// if any of the results becomes NaN, result_valid will evaluate to false // return result_valid ? 0 : -1;
int result_valid = *tA >= 0.0f && *tA <= 1.0f && *tB >= 0.0f && *tB <= 1.0f && *tC >= 0.0f && *tC <= 1.0f; //
//// TIM1->CCR1 = channelA;
return result_valid ? 0 : -1; //// TIM1->CCR2 = channelB;
//// TIM1->CCR3 = channelC;
// TIM1->CCR1 = channelA; //}
// TIM1->CCR2 = channelB;
// TIM1->CCR3 = channelC;
}

View File

@ -1,36 +1,36 @@
////
//// Created by ZK on 2023/3/16.
////
// //
// Created by ZK on 2023/3/16. //#ifndef BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H
//#define BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H
// //
//#include "arm_math.h"
#ifndef BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H
#define BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H
#include "arm_math.h"
//#define M_PI (3.14159265358f)
#define M_2PI (6.28318530716f)
#define ONE_BY_SQRT3 (0.57735026919f)
#define TWO_BY_SQRT3 (2.0f * 0.57735026919f)
#define SQRT3_BY_2 (0.86602540378f)
#define SQ(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define CLAMP(x, lower, upper) (MIN(upper, MAX(x, lower)))
#define FLOAT_EQU(floatA, floatB) ((ABS((floatA) - (floatB))) < 0.000001f)
//extern inline void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta);
// //
//extern inline void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq); ////#define M_PI (3.14159265358f)
//#define M_2PI (6.28318530716f)
extern void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta); //#define ONE_BY_SQRT3 (0.57735026919f)
//#define TWO_BY_SQRT3 (2.0f * 0.57735026919f)
extern void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq); //#define SQRT3_BY_2 (0.86602540378f)
//
extern void inversePark(float ud, float uq, float Theta, float *uAlpha, float *uBeta); //#define SQ(x) ((x) * (x))
//#define ABS(x) ((x) > 0 ? (x) : -(x))
extern int SVPWM(float uAlpha, float uBeta, float *tA, float *tB, float *tC); //#define MAX(x, y) (((x) > (y)) ? (x) : (y))
//#define MIN(x, y) (((x) < (y)) ? (x) : (y))
//#define CLAMP(x, lower, upper) (MIN(upper, MAX(x, lower)))
#endif //BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H //#define FLOAT_EQU(floatA, floatB) ((ABS((floatA) - (floatB))) < 0.000001f)
//
////extern inline void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta);
////
////extern inline void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq);
//
//extern void clarke_transform(float Ia, float Ib, float Ic, float *Ialpha, float *Ibeta);
//
//extern void park_transform(float Ialpha, float Ibeta, float Theta, float *Id, float *Iq);
//
//extern void inversePark(float ud, float uq, float Theta, float *uAlpha, float *uBeta);
//
//extern int SVPWM(float uAlpha, float uBeta, float *tA, float *tB, float *tC);
//
//
//#endif //BOOOOMFOC_STSPIN32G4_EVB_SVPWM_H

View File

@ -1,169 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Angle.h"
#include "usbd_cdc_if.h"
#include "Communication.h"
#define RD_REG_3 0x8300 // 0xffff//
#define RD_REG_4 0x8400 // 0x0000//
//#define POLE_PAIRS 7 //小电机
//双天电机14极飞A1221
//#define POLE_PAIRS 21//大电机
#define POLE_PAIRS 20//大电机
#define LINE_NUM 16384
#define AA_LINE ((float32_t)LINE_NUM / (float32_t)POLE_PAIRS) // 2340.57
#define AA_ANGLE ((float32_t)LINE_NUM / 360.0f) // 45.51
#define BB_ANGLE ((float32_t)AA_LINE / 360.0f) // 6.50
#define ANGLE_RATIO (float32_t)(360.0f / 16384.0f)
//#define OFFSET 680 //小电机
//#define OFFSET 730 //大电机
//#define OFFSET 1020 //大电机
// uint16_t OFFSET_0 = 280;
//uint16_t OFFSET_0 = -10000;
float32_t OFFSET=3000;
#define OFFSET_1 1100
//#define OFFSET_0 30
//#define OFFSET_1 300
uint16_t sendBuf[2] = {RD_REG_3, RD_REG_4};
uint32_t timeout;
float32_t speed, speedFilt, filt = 0.01f;
uint16_t cycleNum;
struct ENCODER_Type encoder0 = {
.hspi = &hspi1,
.CS_Port = GPIOD,
.CS_Pin = GPIO_PIN_2,
.sendBuf = {RD_REG_3, RD_REG_4},
// .offset = OFFSET_0,
};
uint8_t SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint16_t TxData, uint16_t *RxData) {
uint32_t cnt = 0;
while ((hspi->Instance->SR & SPI_SR_TXE) == 0);
hspi->Instance->DR = TxData;
while (cnt < 50) {
if ((hspi->Instance->SR & SPI_SR_RXNE)) {
*RxData = hspi->Instance->DR;
return 0;
}
cnt++;
}
return 1;
}
uint16_t MT_ReadAngle(void) {
HAL_GPIO_WritePin(encoder0.CS_Port, encoder0.CS_Pin, GPIO_PIN_RESET);
timeout = SPI_TransmitReceive(encoder0.hspi, encoder0.sendBuf[0], &encoder0.recvBuf[0]);
HAL_GPIO_WritePin(encoder0.CS_Port, encoder0.CS_Pin, GPIO_PIN_SET);
for (int i = 0; i < 2; i++);
HAL_GPIO_WritePin(encoder0.CS_Port, encoder0.CS_Pin, GPIO_PIN_RESET);
timeout = SPI_TransmitReceive(encoder0.hspi, encoder0.sendBuf[1], &encoder0.recvBuf[1]);
HAL_GPIO_WritePin(encoder0.CS_Port, encoder0.CS_Pin, GPIO_PIN_SET);
/*处理原始数据并转换为机械角度*/
encoder0.angleVal = ((encoder0.recvBuf[0] & 0x00FF) << 6) + ((encoder0.recvBuf[1] & 0x00FF) >> 2);
encoder0.angle_360 = (float32_t) encoder0.angleVal * ANGLE_RATIO;
/*软件记圈*/
if (encoder0.lastAngle > 9000 && encoder0.angleVal < 7000)
encoder0.cycleNum++;
else if (encoder0.lastAngle < 7000 && encoder0.angleVal > 9000)
encoder0.cycleNum--;
/*记速*/
// encoder->angleArr[encoder->cnt][0] = encoder->angleVal;
// encoder->angleArr[encoder->cnt][1] = encoder->cycleNum;
// int32_t temp1 = encoder->angleArr[encoder->cnt][0] - encoder->angleArr[(encoder->cnt +1) % 8][0];
// int32_t temp2 = (encoder->angleArr[encoder->cnt][1] - encoder->angleArr[(encoder->cnt +1) % 8][1]) << 14;
// encoder->speed = (float32_t)(temp1 + temp2) ;// / 32.0f;
// int32_t temp1 = 0;
// int32_t temp2 = 0;
// int32_t sum = 0;
// for(uint8_t i = 0; i < 8 - 1; i++)
// {
// temp1 = encoder->angleArr[i + 1][0] - encoder->angleArr[i][0];
// temp2 = (encoder->angleArr[i + 1][1] - encoder->angleArr[i][1]) << 14;
// sum += (temp1 + temp2) ;// / 32.0f;
// }
// encoder->speed = (float32_t)(sum) / 7.0f;// / 32.0f;
// encoder->cnt ++;
// encoder->cnt &= 0x07;
encoder0.lastAngle = encoder0.angleVal;
return encoder0.angleVal;
}
float32_t GetSpeed(uint16_t angleVal) {
static int32_t lastAngle, lastCycle;
speed = (float32_t) (angleVal - lastAngle + ((encoder0.cycleNum - lastCycle) << 14));
lastAngle = angleVal;
lastCycle = encoder0.cycleNum;
speedFilt = speed * filt + (1.0f - filt) * speedFilt;
return speedFilt;
// return speed;
}
float32_t getAngle_MT6816() {
// float32_t temp = (float32_t)angleVal + (float32_t)encoder0.offset;
// OFFSET+=0.01f;
// usb_printf("%d\r\n", OFFSET);
// if (OFFSET >= 16384.0f){OFFSET= 0.0f;}
float32_t temp = (float32_t) MT_ReadAngle()+16274;
// SendCurrent_Vofa(temp,encoder0.eAngle_360, 0);
while (temp > AA_LINE) {
temp -= AA_LINE;
}
encoder0.eAngle_360 = temp / BB_ANGLE;
// SendCurrent_Vofa(OFFSET,encoder0.eAngle_360, 0);
return encoder0.eAngle_360;
}
//#define EncoderName MT6816
//float32_t getAngle_MT6816() {
//// printf("Test");
//
// return M_PI;
//}
float32_t getAngle_AS5600() {
// printf("Test");
return 0.0f;
}
bool Data_Init(tData *data) {
switch (data->Angle.EncoderModel) {
case MT6816:
data->Angle.getAngle = getAngle_MT6816;
break;
case AS5600:
data->Angle.getAngle = getAngle_AS5600;
break;
}
return 0;
}

View File

@ -1,107 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_ANGLE_H
#define BOOOOMFOC_STSPIN32G4_EVB_ANGLE_H
//#include "APP_Main.h"
#include "arm_math.h"
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "adc.h"
#include "dma.h"
#include "i2c.h"
#include "opamp.h"
#include "spi.h"
#include "tim.h"
#include "usb_device.h"
#include "gpio.h"
typedef enum {
MT6816,
AS5600
} tEncoderModel;
typedef struct {
tEncoderModel EncoderModel;
float32_t (*getAngle)();
} tAngle;
typedef struct {
tAngle Angle;
float32_t (*Angle_Init)();
} tData;
uint16_t MT_ReadAngle(void);
float32_t GetSpeed(uint16_t angleVal);
float32_t getAngle_MT6816();
float32_t getAngle_AS5600();
bool Data_Init(tData *data);
typedef struct sMT6825 {
bool no_mag;
bool over_speed;
uint32_t angle;
uint8_t rx_err_count;
uint8_t check_err_count;
} tMT6825;
typedef struct sEncoder {
int raw;
int count_in_cpr;
int count_in_cpr_prev;
int64_t shadow_count;
// pll use
float pos_cpr_counts;
float vel_estimate_counts;
float pos;
float vel;
float phase;
float phase_vel;
float pll_kp;
float pll_ki;
float interpolation;
float snap_threshold;
} tEncoder;
struct ENCODER_Type {
SPI_HandleTypeDef *hspi;
GPIO_TypeDef *CS_Port;
uint16_t CS_Pin;
uint16_t sendBuf[2];
uint16_t recvBuf[2];
uint16_t offset;
uint16_t angleVal, lastAngle;
int32_t cycleNum;
float32_t angle_360;
float32_t eAngle_360;
// int32_t angleArr[32][2];
// uint8_t cnt;
float32_t speed;
float32_t filt;
float32_t speedFilt;
};
#endif //BOOOOMFOC_STSPIN32G4_EVB_ANGLE_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "MT6816.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_MT6816_H
#define BOOOOMFOC_STSPIN32G4_EVB_MT6816_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_MT6816_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Current.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_CURRENT_H
#define BOOOOMFOC_STSPIN32G4_EVB_CURRENT_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_CURRENT_H

View File

@ -1,22 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "InteriorADC.h"
bool InteriorADC_Init(void) {
//使能ADC注入
HAL_ADCEx_Calibration_Start(&hadc1, ADC_SINGLE_ENDED);
HAL_ADCEx_Calibration_Start(&hadc2, ADC_SINGLE_ENDED);
HAL_Delay(100);
HAL_ADCEx_InjectedStart(&hadc1);
__HAL_ADC_ENABLE_IT(&hadc1, ADC_IT_JEOC);
__HAL_ADC_DISABLE_IT(&hadc1, ADC_IT_JEOS);//关闭ADC1的中断避免ADC1_2_IRQHandler触发两次
HAL_ADCEx_InjectedStart(&hadc2);
__HAL_ADC_ENABLE_IT(&hadc2, ADC_IT_JEOC);
return 0;//返回值为零表示初始化成功
}

View File

@ -1,12 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_INTERIORADC_H
#define BOOOOMFOC_STSPIN32G4_EVB_INTERIORADC_H
#include "APP_Main.h"
bool InteriorADC_Init(void);
#endif //BOOOOMFOC_STSPIN32G4_EVB_INTERIORADC_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Data.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_DATA_H
#define BOOOOMFOC_STSPIN32G4_EVB_DATA_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_DATA_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Temperature.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_TEMPERATURE_H
#define BOOOOMFOC_STSPIN32G4_EVB_TEMPERATURE_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_TEMPERATURE_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Voltage.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_VOLTAGE_H
#define BOOOOMFOC_STSPIN32G4_EVB_VOLTAGE_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_VOLTAGE_H

View File

@ -1,5 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#include "Parameter.h"

View File

@ -1,8 +0,0 @@
//
// Created by ZK on 2023/3/14.
//
#ifndef BOOOOMFOC_STSPIN32G4_EVB_PARAMETER_H
#define BOOOOMFOC_STSPIN32G4_EVB_PARAMETER_H
#endif //BOOOOMFOC_STSPIN32G4_EVB_PARAMETER_H

View File

@ -15,6 +15,7 @@ source [find interface/stlink.cfg]
transport select hla_swd transport select hla_swd
source [find target/stm32g4x.cfg] source [find target/stm32g4x.cfg]
adapter_khz 500
;reset_config srst_only ;reset_config srst_only
reset_config none reset_config none

View File

@ -78,11 +78,67 @@ Dma.ADC1.0.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Dma.ADC1.0.SyncRequestNumber=1 Dma.ADC1.0.SyncRequestNumber=1
Dma.ADC1.0.SyncSignalID=NONE Dma.ADC1.0.SyncSignalID=NONE
Dma.Request0=ADC1 Dma.Request0=ADC1
Dma.RequestsNb=1 Dma.Request1=USART1_RX
Dma.Request2=USART1_TX
Dma.Request3=TIM8_CH1
Dma.RequestsNb=4
Dma.TIM8_CH1.3.Direction=DMA_MEMORY_TO_PERIPH
Dma.TIM8_CH1.3.EventEnable=DISABLE
Dma.TIM8_CH1.3.Instance=DMA1_Channel6
Dma.TIM8_CH1.3.MemDataAlignment=DMA_MDATAALIGN_BYTE
Dma.TIM8_CH1.3.MemInc=DMA_MINC_ENABLE
Dma.TIM8_CH1.3.Mode=DMA_CIRCULAR
Dma.TIM8_CH1.3.PeriphDataAlignment=DMA_PDATAALIGN_WORD
Dma.TIM8_CH1.3.PeriphInc=DMA_PINC_DISABLE
Dma.TIM8_CH1.3.Polarity=HAL_DMAMUX_REQ_GEN_RISING
Dma.TIM8_CH1.3.Priority=DMA_PRIORITY_LOW
Dma.TIM8_CH1.3.RequestNumber=1
Dma.TIM8_CH1.3.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,SignalID,Polarity,RequestNumber,SyncSignalID,SyncPolarity,SyncEnable,EventEnable,SyncRequestNumber
Dma.TIM8_CH1.3.SignalID=NONE
Dma.TIM8_CH1.3.SyncEnable=DISABLE
Dma.TIM8_CH1.3.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Dma.TIM8_CH1.3.SyncRequestNumber=1
Dma.TIM8_CH1.3.SyncSignalID=NONE
Dma.USART1_RX.1.Direction=DMA_PERIPH_TO_MEMORY
Dma.USART1_RX.1.EventEnable=DISABLE
Dma.USART1_RX.1.Instance=DMA2_Channel1
Dma.USART1_RX.1.MemDataAlignment=DMA_MDATAALIGN_BYTE
Dma.USART1_RX.1.MemInc=DMA_MINC_ENABLE
Dma.USART1_RX.1.Mode=DMA_CIRCULAR
Dma.USART1_RX.1.PeriphDataAlignment=DMA_PDATAALIGN_BYTE
Dma.USART1_RX.1.PeriphInc=DMA_PINC_DISABLE
Dma.USART1_RX.1.Polarity=HAL_DMAMUX_REQ_GEN_RISING
Dma.USART1_RX.1.Priority=DMA_PRIORITY_MEDIUM
Dma.USART1_RX.1.RequestNumber=1
Dma.USART1_RX.1.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,SignalID,Polarity,RequestNumber,SyncSignalID,SyncPolarity,SyncEnable,EventEnable,SyncRequestNumber
Dma.USART1_RX.1.SignalID=NONE
Dma.USART1_RX.1.SyncEnable=DISABLE
Dma.USART1_RX.1.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Dma.USART1_RX.1.SyncRequestNumber=1
Dma.USART1_RX.1.SyncSignalID=NONE
Dma.USART1_TX.2.Direction=DMA_MEMORY_TO_PERIPH
Dma.USART1_TX.2.EventEnable=DISABLE
Dma.USART1_TX.2.Instance=DMA2_Channel2
Dma.USART1_TX.2.MemDataAlignment=DMA_MDATAALIGN_BYTE
Dma.USART1_TX.2.MemInc=DMA_MINC_ENABLE
Dma.USART1_TX.2.Mode=DMA_NORMAL
Dma.USART1_TX.2.PeriphDataAlignment=DMA_PDATAALIGN_BYTE
Dma.USART1_TX.2.PeriphInc=DMA_PINC_DISABLE
Dma.USART1_TX.2.Polarity=HAL_DMAMUX_REQ_GEN_RISING
Dma.USART1_TX.2.Priority=DMA_PRIORITY_MEDIUM
Dma.USART1_TX.2.RequestNumber=1
Dma.USART1_TX.2.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,SignalID,Polarity,RequestNumber,SyncSignalID,SyncPolarity,SyncEnable,EventEnable,SyncRequestNumber
Dma.USART1_TX.2.SignalID=NONE
Dma.USART1_TX.2.SyncEnable=DISABLE
Dma.USART1_TX.2.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Dma.USART1_TX.2.SyncRequestNumber=1
Dma.USART1_TX.2.SyncSignalID=NONE
File.Version=6 File.Version=6
GPIO.groupedBy=Group By Peripherals GPIO.groupedBy=Group By Peripherals
I2C3.IPParameters=Timing I2C1.I2C_Speed_Mode=I2C_Standard
I2C3.Timing=0x60505F8C I2C1.IPParameters=Timing,I2C_Speed_Mode,Speed
I2C1.Speed=50
I2C1.Timing=0x6050DCFF
KeepUserPlacement=false KeepUserPlacement=false
Mcu.CPN=STM32G431VBT3 Mcu.CPN=STM32G431VBT3
Mcu.Family=STM32G4 Mcu.Family=STM32G4
@ -90,10 +146,10 @@ Mcu.IP0=ADC1
Mcu.IP1=ADC2 Mcu.IP1=ADC2
Mcu.IP10=SYS Mcu.IP10=SYS
Mcu.IP11=TIM1 Mcu.IP11=TIM1
Mcu.IP12=USB Mcu.IP12=TIM8
Mcu.IP13=USB_DEVICE Mcu.IP13=USART1
Mcu.IP2=DMA Mcu.IP2=DMA
Mcu.IP3=I2C3 Mcu.IP3=I2C1
Mcu.IP4=NVIC Mcu.IP4=NVIC
Mcu.IP5=OPAMP1 Mcu.IP5=OPAMP1
Mcu.IP6=OPAMP2 Mcu.IP6=OPAMP2
@ -103,56 +159,56 @@ Mcu.IP9=SPI1
Mcu.IPNb=14 Mcu.IPNb=14
Mcu.Name=STM32G431V(6-8-B)Tx Mcu.Name=STM32G431V(6-8-B)Tx
Mcu.Package=LQFP100 Mcu.Package=LQFP100
Mcu.Pin0=PF0-OSC_IN Mcu.Pin0=PC13
Mcu.Pin1=PF1-OSC_OUT Mcu.Pin1=PF0-OSC_IN
Mcu.Pin10=PA7 Mcu.Pin10=PA5
Mcu.Pin11=PC5 Mcu.Pin11=PA6
Mcu.Pin12=PB0 Mcu.Pin12=PA7
Mcu.Pin13=PB1 Mcu.Pin13=PB0
Mcu.Pin14=PB2 Mcu.Pin14=PB1
Mcu.Pin15=PE7 Mcu.Pin15=PB2
Mcu.Pin16=PE8 Mcu.Pin16=PB13
Mcu.Pin17=PE9 Mcu.Pin17=PB14
Mcu.Pin18=PE10 Mcu.Pin18=PB15
Mcu.Pin19=PE11 Mcu.Pin19=PC6
Mcu.Pin2=PC0 Mcu.Pin2=PF1-OSC_OUT
Mcu.Pin20=PE12 Mcu.Pin20=PA8
Mcu.Pin21=PE13 Mcu.Pin21=PA9
Mcu.Pin22=PE14 Mcu.Pin22=PA10
Mcu.Pin23=PE15 Mcu.Pin23=PA13
Mcu.Pin24=PB10 Mcu.Pin24=PA14
Mcu.Pin25=PC8 Mcu.Pin25=PB3
Mcu.Pin26=PC9 Mcu.Pin26=PB4
Mcu.Pin27=PA11 Mcu.Pin27=PB5
Mcu.Pin28=PA12 Mcu.Pin28=PB6
Mcu.Pin29=PA13 Mcu.Pin29=PB7
Mcu.Pin3=PC1 Mcu.Pin3=PC0
Mcu.Pin30=PA14 Mcu.Pin30=PB8-BOOT0
Mcu.Pin31=PD2 Mcu.Pin31=PB9
Mcu.Pin32=PB3 Mcu.Pin32=VP_ADC1_TempSens_Input
Mcu.Pin33=PB4 Mcu.Pin33=VP_SYS_VS_Systick
Mcu.Pin34=PB5 Mcu.Pin34=VP_SYS_VS_DBSignals
Mcu.Pin35=VP_ADC1_TempSens_Input Mcu.Pin35=VP_TIM1_VS_ClockSourceINT
Mcu.Pin36=VP_SYS_VS_Systick Mcu.Pin36=VP_TIM1_VS_no_output4
Mcu.Pin37=VP_SYS_VS_DBSignals Mcu.Pin37=VP_TIM8_VS_ClockSourceINT
Mcu.Pin38=VP_TIM1_VS_ClockSourceINT Mcu.Pin4=PC1
Mcu.Pin39=VP_TIM1_VS_no_output4 Mcu.Pin5=PC2
Mcu.Pin4=PC2 Mcu.Pin6=PA0
Mcu.Pin40=VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS Mcu.Pin7=PA1
Mcu.Pin5=PA0 Mcu.Pin8=PA2
Mcu.Pin6=PA1 Mcu.Pin9=PA3
Mcu.Pin7=PA2 Mcu.PinsNb=38
Mcu.Pin8=PA3
Mcu.Pin9=PA6
Mcu.PinsNb=41
Mcu.ThirdPartyNb=0 Mcu.ThirdPartyNb=0
Mcu.UserConstants= Mcu.UserConstants=
Mcu.UserName=STM32G431VBTx Mcu.UserName=STM32G431VBTx
MxCube.Version=6.8.0 MxCube.Version=6.8.0
MxDb.Version=DB.6.0.80 MxDb.Version=DB.6.0.80
NVIC.ADC1_2_IRQn=true\:1\:0\:true\:false\:true\:true\:true\:true NVIC.ADC1_2_IRQn=true\:0\:0\:true\:false\:true\:true\:true\:true
NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
NVIC.DMA1_Channel1_IRQn=true\:2\:0\:true\:false\:true\:false\:true\:true NVIC.DMA1_Channel1_IRQn=true\:15\:0\:true\:false\:true\:false\:true\:true
NVIC.DMA1_Channel6_IRQn=true\:15\:0\:true\:false\:true\:false\:true\:true
NVIC.DMA2_Channel1_IRQn=true\:2\:0\:true\:false\:true\:false\:true\:true
NVIC.DMA2_Channel2_IRQn=true\:2\:0\:true\:false\:true\:false\:true\:true
NVIC.DebugMonitor_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.DebugMonitor_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
NVIC.ForceEnableDMAVector=true NVIC.ForceEnableDMAVector=true
NVIC.HardFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.HardFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
@ -161,9 +217,9 @@ NVIC.NonMaskableInt_IRQn=true\:0\:0\:false\:false\:true\:false\:true\:false
NVIC.PendSV_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.PendSV_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
NVIC.PriorityGroup=NVIC_PRIORITYGROUP_4 NVIC.PriorityGroup=NVIC_PRIORITYGROUP_4
NVIC.SVCall_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.SVCall_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
NVIC.SysTick_IRQn=true\:15\:0\:true\:false\:true\:false\:true\:false NVIC.SysTick_IRQn=true\:7\:0\:true\:false\:true\:false\:true\:false
NVIC.TIM1_UP_TIM16_IRQn=true\:15\:0\:true\:false\:true\:true\:true\:true NVIC.TIM1_UP_TIM16_IRQn=true\:1\:0\:true\:false\:true\:true\:true\:true
NVIC.USB_LP_IRQn=true\:0\:0\:false\:false\:true\:false\:true\:true NVIC.USART1_IRQn=true\:2\:0\:true\:false\:true\:true\:true\:true
NVIC.UsageFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.UsageFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false
PA0.Locked=true PA0.Locked=true
PA0.Mode=IN1-Single-Ended PA0.Mode=IN1-Single-Ended
@ -171,10 +227,8 @@ PA0.Signal=ADC1_IN1
PA1.Locked=true PA1.Locked=true
PA1.Mode=Standalone PA1.Mode=Standalone
PA1.Signal=OPAMP1_VINP PA1.Signal=OPAMP1_VINP
PA11.Mode=Device PA10.Locked=true
PA11.Signal=USB_DM PA10.Signal=S_TIM1_CH3
PA12.Mode=Device
PA12.Signal=USB_DP
PA13.Mode=Serial_Wire PA13.Mode=Serial_Wire
PA13.Signal=SYS_JTMS-SWDIO PA13.Signal=SYS_JTMS-SWDIO
PA14.Mode=Serial_Wire PA14.Mode=Serial_Wire
@ -184,18 +238,32 @@ PA2.Signal=SharedAnalog_PA2
PA3.Locked=true PA3.Locked=true
PA3.Mode=Standalone PA3.Mode=Standalone
PA3.Signal=OPAMP1_VINM PA3.Signal=OPAMP1_VINM
PA5.Locked=true
PA5.Mode=Standalone
PA5.Signal=OPAMP2_VINM
PA6.Locked=true PA6.Locked=true
PA6.Signal=SharedAnalog_PA6 PA6.Signal=SharedAnalog_PA6
PA7.Locked=true PA7.Locked=true
PA7.Mode=Standalone PA7.Mode=Standalone
PA7.Signal=OPAMP2_VINP PA7.Signal=OPAMP2_VINP
PA8.Locked=true
PA8.Signal=S_TIM1_CH1
PA9.Locked=true
PA9.Signal=S_TIM1_CH2
PB0.Locked=true PB0.Locked=true
PB0.Mode=Standalone PB0.Mode=Standalone
PB0.Signal=OPAMP3_VINP PB0.Signal=OPAMP3_VINP
PB1.Locked=true PB1.Locked=true
PB1.Signal=SharedAnalog_PB1 PB1.Signal=SharedAnalog_PB1
PB10.Locked=true PB13.Locked=true
PB10.Signal=GPIO_Input PB13.Mode=PWM Generation1 CH1 CH1N
PB13.Signal=TIM1_CH1N
PB14.Locked=true
PB14.Mode=PWM Generation2 CH2 CH2N
PB14.Signal=TIM1_CH2N
PB15.Locked=true
PB15.Mode=PWM Generation3 CH3 CH3N
PB15.Signal=TIM1_CH3N
PB2.Locked=true PB2.Locked=true
PB2.Mode=Standalone PB2.Mode=Standalone
PB2.Signal=OPAMP3_VINM PB2.Signal=OPAMP3_VINM
@ -215,52 +283,41 @@ PB5.GPIO_Speed=GPIO_SPEED_FREQ_VERY_HIGH
PB5.Locked=true PB5.Locked=true
PB5.Mode=Full_Duplex_Master PB5.Mode=Full_Duplex_Master
PB5.Signal=SPI1_MOSI PB5.Signal=SPI1_MOSI
PB6.Locked=true
PB6.Mode=Asynchronous
PB6.Signal=USART1_TX
PB7.Locked=true
PB7.Mode=Asynchronous
PB7.Signal=USART1_RX
PB8-BOOT0.GPIOParameters=GPIO_Speed,GPIO_FM8
PB8-BOOT0.GPIO_FM8=SYSCFG_FASTMODEPLUS_PB8
PB8-BOOT0.GPIO_Speed=GPIO_SPEED_FREQ_HIGH
PB8-BOOT0.Locked=true
PB8-BOOT0.Mode=I2C
PB8-BOOT0.Signal=I2C1_SCL
PB9.GPIOParameters=GPIO_Speed,GPIO_FM9
PB9.GPIO_FM9=SYSCFG_FASTMODEPLUS_PB9
PB9.GPIO_Speed=GPIO_SPEED_FREQ_HIGH
PB9.Locked=true
PB9.Mode=I2C
PB9.Signal=I2C1_SDA
PC0.Locked=true PC0.Locked=true
PC0.Mode=IN6-Single-Ended PC0.Mode=IN6-Single-Ended
PC0.Signal=ADC2_IN6 PC0.Signal=ADC2_IN6
PC1.Locked=true PC1.Locked=true
PC1.Mode=IN7-Single-Ended PC1.Mode=IN7-Single-Ended
PC1.Signal=ADC2_IN7 PC1.Signal=ADC2_IN7
PC13.GPIOParameters=GPIO_Label
PC13.GPIO_Label=SPI1_CS
PC13.Locked=true
PC13.Signal=GPIO_Output
PC2.Locked=true PC2.Locked=true
PC2.Mode=IN8-Single-Ended PC2.Mode=IN8-Single-Ended
PC2.Signal=ADC2_IN8 PC2.Signal=ADC2_IN8
PC5.Locked=true PC6.GPIOParameters=GPIO_PuPd
PC5.Mode=Standalone PC6.GPIO_PuPd=GPIO_PULLUP
PC5.Signal=OPAMP2_VINM PC6.Locked=true
PC8.Locked=true PC6.Signal=S_TIM8_CH1
PC8.Mode=I2C
PC8.Signal=I2C3_SCL
PC9.Locked=true
PC9.Mode=I2C
PC9.Signal=I2C3_SDA
PD2.GPIOParameters=PinState,GPIO_Label
PD2.GPIO_Label=SPI1_CS
PD2.Locked=true
PD2.PinState=GPIO_PIN_RESET
PD2.Signal=GPIO_Output
PE10.Locked=true
PE10.Mode=PWM Generation2 CH2 CH2N
PE10.Signal=TIM1_CH2N
PE11.Locked=true
PE11.Signal=S_TIM1_CH2
PE12.Locked=true
PE12.Mode=PWM Generation3 CH3 CH3N
PE12.Signal=TIM1_CH3N
PE13.Locked=true
PE13.Signal=S_TIM1_CH3
PE14.Locked=true
PE14.Signal=GPIO_Input
PE15.GPIOParameters=GPIO_PuPd
PE15.GPIO_PuPd=GPIO_PULLUP
PE15.Locked=true
PE15.Signal=GPIO_Input
PE7.Locked=true
PE7.Signal=GPIO_Output
PE8.Locked=true
PE8.Mode=PWM Generation1 CH1 CH1N
PE8.Signal=TIM1_CH1N
PE9.Locked=true
PE9.Signal=S_TIM1_CH1
PF0-OSC_IN.Mode=HSE-External-Oscillator PF0-OSC_IN.Mode=HSE-External-Oscillator
PF0-OSC_IN.Signal=RCC_OSC_IN PF0-OSC_IN.Signal=RCC_OSC_IN
PF1-OSC_OUT.Mode=HSE-External-Oscillator PF1-OSC_OUT.Mode=HSE-External-Oscillator
@ -293,8 +350,10 @@ ProjectManager.RegisterCallBack=
ProjectManager.StackSize=0x400 ProjectManager.StackSize=0x400
ProjectManager.TargetToolchain=STM32CubeIDE ProjectManager.TargetToolchain=STM32CubeIDE
ProjectManager.ToolChainLocation= ProjectManager.ToolChainLocation=
ProjectManager.UAScriptAfterPath=
ProjectManager.UAScriptBeforePath=
ProjectManager.UnderRoot=true ProjectManager.UnderRoot=true
ProjectManager.functionlistsort=1-SystemClock_Config-RCC-false-HAL-false,2-MX_GPIO_Init-GPIO-false-HAL-true,3-MX_DMA_Init-DMA-false-HAL-true,4-MX_TIM1_Init-TIM1-false-HAL-true,5-MX_ADC1_Init-ADC1-false-HAL-true,6-MX_I2C3_Init-I2C3-false-HAL-true,7-MX_OPAMP1_Init-OPAMP1-false-HAL-true,8-MX_OPAMP2_Init-OPAMP2-false-HAL-true,9-MX_OPAMP3_Init-OPAMP3-false-HAL-true,10-MX_ADC2_Init-ADC2-false-HAL-true,11-MX_USB_Device_Init-USB_DEVICE-false-HAL-false,12-MX_SPI1_Init-SPI1-false-HAL-true ProjectManager.functionlistsort=1-SystemClock_Config-RCC-false-HAL-false,2-MX_GPIO_Init-GPIO-false-HAL-true,3-MX_DMA_Init-DMA-false-HAL-true,4-MX_TIM1_Init-TIM1-false-HAL-true,5-MX_ADC1_Init-ADC1-false-HAL-true,6-MX_OPAMP1_Init-OPAMP1-false-HAL-true,7-MX_OPAMP2_Init-OPAMP2-false-HAL-true,8-MX_OPAMP3_Init-OPAMP3-false-HAL-true,9-MX_ADC2_Init-ADC2-false-HAL-true,10-MX_SPI1_Init-SPI1-false-HAL-true,11-MX_USART1_UART_Init-USART1-false-HAL-true,12-MX_I2C1_Init-I2C1-false-HAL-true,13-MX_TIM8_Init-TIM8-false-HAL-true
RCC.ADC12Freq_Value=168000000 RCC.ADC12Freq_Value=168000000
RCC.AHBFreq_Value=168000000 RCC.AHBFreq_Value=168000000
RCC.APB1Freq_Value=168000000 RCC.APB1Freq_Value=168000000
@ -348,19 +407,21 @@ SH.S_TIM1_CH2.0=TIM1_CH2,PWM Generation2 CH2 CH2N
SH.S_TIM1_CH2.ConfNb=1 SH.S_TIM1_CH2.ConfNb=1
SH.S_TIM1_CH3.0=TIM1_CH3,PWM Generation3 CH3 CH3N SH.S_TIM1_CH3.0=TIM1_CH3,PWM Generation3 CH3 CH3N
SH.S_TIM1_CH3.ConfNb=1 SH.S_TIM1_CH3.ConfNb=1
SH.S_TIM8_CH1.0=TIM8_CH1,PWM Generation1 CH1
SH.S_TIM8_CH1.ConfNb=1
SH.SharedAnalog_PA2.0=OPAMP1_VOUT,Standalone SH.SharedAnalog_PA2.0=OPAMP1_VOUT,Standalone
SH.SharedAnalog_PA2.1=ADC1_IN3,IN3-Single-Ended SH.SharedAnalog_PA2.1=ADC1_IN3,IN3-Single-Ended
SH.SharedAnalog_PA2.ConfNb=2 SH.SharedAnalog_PA2.ConfNb=2
SH.SharedAnalog_PA6.0=OPAMP2_VOUT,Standalone SH.SharedAnalog_PA6.0=ADC2_IN3,IN3-Single-Ended
SH.SharedAnalog_PA6.1=ADC2_IN3,IN3-Single-Ended SH.SharedAnalog_PA6.1=OPAMP2_VOUT,Standalone
SH.SharedAnalog_PA6.ConfNb=2 SH.SharedAnalog_PA6.ConfNb=2
SH.SharedAnalog_PB1.0=OPAMP3_VOUT,Standalone SH.SharedAnalog_PB1.0=OPAMP3_VOUT,Standalone
SH.SharedAnalog_PB1.1=ADC1_IN12,IN12-Single-Ended SH.SharedAnalog_PB1.1=ADC1_IN12,IN12-Single-Ended
SH.SharedAnalog_PB1.ConfNb=2 SH.SharedAnalog_PB1.ConfNb=2
SPI1.BaudRatePrescaler=SPI_BAUDRATEPRESCALER_16 SPI1.BaudRatePrescaler=SPI_BAUDRATEPRESCALER_32
SPI1.CLKPhase=SPI_PHASE_2EDGE SPI1.CLKPhase=SPI_PHASE_2EDGE
SPI1.CLKPolarity=SPI_POLARITY_HIGH SPI1.CLKPolarity=SPI_POLARITY_HIGH
SPI1.CalculateBaudRate=10.5 MBits/s SPI1.CalculateBaudRate=5.25 MBits/s
SPI1.DataSize=SPI_DATASIZE_16BIT SPI1.DataSize=SPI_DATASIZE_16BIT
SPI1.Direction=SPI_DIRECTION_2LINES SPI1.Direction=SPI_DIRECTION_2LINES
SPI1.IPParameters=VirtualType,Mode,Direction,BaudRatePrescaler,CalculateBaudRate,CLKPolarity,CLKPhase,DataSize SPI1.IPParameters=VirtualType,Mode,Direction,BaudRatePrescaler,CalculateBaudRate,CLKPolarity,CLKPhase,DataSize
@ -378,10 +439,17 @@ TIM1.PeriodNoDither=3500
TIM1.Prescaler=0 TIM1.Prescaler=0
TIM1.PulseNoDither_4=3450 TIM1.PulseNoDither_4=3450
TIM1.TIM_MasterOutputTrigger=TIM_TRGO_OC4REF TIM1.TIM_MasterOutputTrigger=TIM_TRGO_OC4REF
USB_DEVICE.CLASS_NAME_FS=CDC TIM8.AutoReloadPreload=TIM_AUTORELOAD_PRELOAD_ENABLE
USB_DEVICE.IPParameters=VirtualMode,VirtualModeFS,CLASS_NAME_FS TIM8.Channel-PWM\ Generation1\ CH1=TIM_CHANNEL_1
USB_DEVICE.VirtualMode=Cdc TIM8.IPParameters=Channel-PWM Generation1 CH1,Prescaler,PeriodNoDither,AutoReloadPreload
USB_DEVICE.VirtualModeFS=Cdc_FS TIM8.PeriodNoDither=209
TIM8.Prescaler=0
USART1.AutoBaudRateEnableParam=UART_ADVFEATURE_AUTOBAUDRATE_DISABLE
USART1.BaudRate=8000000
USART1.DMADisableonRxErrorParam=ADVFEATURE_DMA_DISABLEONRXERROR
USART1.IPParameters=VirtualMode-Asynchronous,AutoBaudRateEnableParam,BaudRate,OverrunDisableParam,DMADisableonRxErrorParam
USART1.OverrunDisableParam=ADVFEATURE_OVERRUN_DISABLE
USART1.VirtualMode-Asynchronous=VM_ASYNC
VP_ADC1_TempSens_Input.Mode=IN-TempSens VP_ADC1_TempSens_Input.Mode=IN-TempSens
VP_ADC1_TempSens_Input.Signal=ADC1_TempSens_Input VP_ADC1_TempSens_Input.Signal=ADC1_TempSens_Input
VP_SYS_VS_DBSignals.Mode=DisableDeadBatterySignals VP_SYS_VS_DBSignals.Mode=DisableDeadBatterySignals
@ -392,6 +460,6 @@ VP_TIM1_VS_ClockSourceINT.Mode=Internal
VP_TIM1_VS_ClockSourceINT.Signal=TIM1_VS_ClockSourceINT VP_TIM1_VS_ClockSourceINT.Signal=TIM1_VS_ClockSourceINT
VP_TIM1_VS_no_output4.Mode=PWM Generation4 No Output VP_TIM1_VS_no_output4.Mode=PWM Generation4 No Output
VP_TIM1_VS_no_output4.Signal=TIM1_VS_no_output4 VP_TIM1_VS_no_output4.Signal=TIM1_VS_no_output4
VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Mode=CDC_FS VP_TIM8_VS_ClockSourceINT.Mode=Internal
VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Signal=USB_DEVICE_VS_USB_DEVICE_CDC_FS VP_TIM8_VS_ClockSourceINT.Signal=TIM8_VS_ClockSourceINT
board=custom board=custom

View File

@ -7,7 +7,7 @@
****************************************************************************** ******************************************************************************
* @attention * @attention
* *
* Copyright (c) 2023 STMicroelectronics. * Copyright (c) 2024 STMicroelectronics.
* All rights reserved. * All rights reserved.
* *
* This software is licensed under terms that can be found in the LICENSE file * This software is licensed under terms that can be found in the LICENSE file
@ -32,13 +32,13 @@ extern "C" {
/* USER CODE END Includes */ /* USER CODE END Includes */
extern I2C_HandleTypeDef hi2c3; extern I2C_HandleTypeDef hi2c1;
/* USER CODE BEGIN Private defines */ /* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */ /* USER CODE END Private defines */
void MX_I2C3_Init(void); void MX_I2C1_Init(void);
/* USER CODE BEGIN Prototypes */ /* USER CODE BEGIN Prototypes */

View File

@ -31,6 +31,9 @@ extern "C" {
/* Private includes ----------------------------------------------------------*/ /* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */ /* USER CODE BEGIN Includes */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/* USER CODE END Includes */ /* USER CODE END Includes */
@ -57,8 +60,8 @@ void Error_Handler(void);
/* USER CODE END EFP */ /* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/
#define SPI1_CS_Pin GPIO_PIN_2 #define SPI1_CS_Pin GPIO_PIN_13
#define SPI1_CS_GPIO_Port GPIOD #define SPI1_CS_GPIO_Port GPIOC
/* USER CODE BEGIN Private defines */ /* USER CODE BEGIN Private defines */

View File

@ -53,7 +53,7 @@
/*#define HAL_NAND_MODULE_ENABLED */ /*#define HAL_NAND_MODULE_ENABLED */
/*#define HAL_NOR_MODULE_ENABLED */ /*#define HAL_NOR_MODULE_ENABLED */
#define HAL_OPAMP_MODULE_ENABLED #define HAL_OPAMP_MODULE_ENABLED
#define HAL_PCD_MODULE_ENABLED /*#define HAL_PCD_MODULE_ENABLED */
/*#define HAL_QSPI_MODULE_ENABLED */ /*#define HAL_QSPI_MODULE_ENABLED */
/*#define HAL_RNG_MODULE_ENABLED */ /*#define HAL_RNG_MODULE_ENABLED */
/*#define HAL_RTC_MODULE_ENABLED */ /*#define HAL_RTC_MODULE_ENABLED */
@ -63,7 +63,7 @@
#define HAL_SPI_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED
/*#define HAL_SRAM_MODULE_ENABLED */ /*#define HAL_SRAM_MODULE_ENABLED */
#define HAL_TIM_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED
/*#define HAL_UART_MODULE_ENABLED */ #define HAL_UART_MODULE_ENABLED
/*#define HAL_USART_MODULE_ENABLED */ /*#define HAL_USART_MODULE_ENABLED */
/*#define HAL_WWDG_MODULE_ENABLED */ /*#define HAL_WWDG_MODULE_ENABLED */
#define HAL_GPIO_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED
@ -181,7 +181,7 @@ The real value may vary depending on the variations in voltage and temperature.*
*/ */
#define VDD_VALUE (3300UL) /*!< Value of VDD in mv */ #define VDD_VALUE (3300UL) /*!< Value of VDD in mv */
#define TICK_INT_PRIORITY (15UL) /*!< tick interrupt priority (lowest by default) */ #define TICK_INT_PRIORITY (7UL) /*!< tick interrupt priority (lowest by default) */
#define USE_RTOS 0U #define USE_RTOS 0U
#define PREFETCH_ENABLE 0U #define PREFETCH_ENABLE 0U
#define INSTRUCTION_CACHE_ENABLE 1U #define INSTRUCTION_CACHE_ENABLE 1U

View File

@ -56,9 +56,12 @@ void DebugMon_Handler(void);
void PendSV_Handler(void); void PendSV_Handler(void);
void SysTick_Handler(void); void SysTick_Handler(void);
void DMA1_Channel1_IRQHandler(void); void DMA1_Channel1_IRQHandler(void);
void DMA1_Channel6_IRQHandler(void);
void ADC1_2_IRQHandler(void); void ADC1_2_IRQHandler(void);
void USB_LP_IRQHandler(void);
void TIM1_UP_TIM16_IRQHandler(void); void TIM1_UP_TIM16_IRQHandler(void);
void USART1_IRQHandler(void);
void DMA2_Channel1_IRQHandler(void);
void DMA2_Channel2_IRQHandler(void);
/* USER CODE BEGIN EFP */ /* USER CODE BEGIN EFP */
/* USER CODE END EFP */ /* USER CODE END EFP */

View File

@ -34,11 +34,14 @@ extern "C" {
extern TIM_HandleTypeDef htim1; extern TIM_HandleTypeDef htim1;
extern TIM_HandleTypeDef htim8;
/* USER CODE BEGIN Private defines */ /* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */ /* USER CODE END Private defines */
void MX_TIM1_Init(void); void MX_TIM1_Init(void);
void MX_TIM8_Init(void);
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim); void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);

View File

@ -281,7 +281,7 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
__HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1); __HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);
/* ADC1 interrupt Init */ /* ADC1 interrupt Init */
HAL_NVIC_SetPriority(ADC1_2_IRQn, 1, 0); HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(ADC1_2_IRQn); HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
/* USER CODE BEGIN ADC1_MspInit 1 */ /* USER CODE BEGIN ADC1_MspInit 1 */
@ -327,7 +327,7 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* ADC2 interrupt Init */ /* ADC2 interrupt Init */
HAL_NVIC_SetPriority(ADC1_2_IRQn, 1, 0); HAL_NVIC_SetPriority(ADC1_2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(ADC1_2_IRQn); HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
/* USER CODE BEGIN ADC2_MspInit 1 */ /* USER CODE BEGIN ADC2_MspInit 1 */

View File

@ -42,11 +42,21 @@ void MX_DMA_Init(void)
/* DMA controller clock enable */ /* DMA controller clock enable */
__HAL_RCC_DMAMUX1_CLK_ENABLE(); __HAL_RCC_DMAMUX1_CLK_ENABLE();
__HAL_RCC_DMA1_CLK_ENABLE(); __HAL_RCC_DMA1_CLK_ENABLE();
__HAL_RCC_DMA2_CLK_ENABLE();
/* DMA interrupt init */ /* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */ /* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 2, 0); HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn); HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* DMA1_Channel6_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
/* DMA2_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Channel1_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Channel1_IRQn);
/* DMA2_Channel2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Channel2_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Channel2_IRQn);
} }

View File

@ -45,44 +45,14 @@ void MX_GPIO_Init(void)
GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */ /* GPIO Ports Clock Enable */
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_7, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */ /*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET); HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : PE7 */
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : PE14 */
GPIO_InitStruct.Pin = GPIO_PIN_14;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : PE15 */
GPIO_InitStruct.Pin = GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : PB10 */
GPIO_InitStruct.Pin = GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : PtPin */ /*Configure GPIO pin : PtPin */
GPIO_InitStruct.Pin = SPI1_CS_Pin; GPIO_InitStruct.Pin = SPI1_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;

View File

@ -7,7 +7,7 @@
****************************************************************************** ******************************************************************************
* @attention * @attention
* *
* Copyright (c) 2023 STMicroelectronics. * Copyright (c) 2024 STMicroelectronics.
* All rights reserved. * All rights reserved.
* *
* This software is licensed under terms that can be found in the LICENSE file * This software is licensed under terms that can be found in the LICENSE file
@ -24,49 +24,49 @@
/* USER CODE END 0 */ /* USER CODE END 0 */
I2C_HandleTypeDef hi2c3; I2C_HandleTypeDef hi2c1;
/* I2C3 init function */ /* I2C1 init function */
void MX_I2C3_Init(void) void MX_I2C1_Init(void)
{ {
/* USER CODE BEGIN I2C3_Init 0 */ /* USER CODE BEGIN I2C1_Init 0 */
/* USER CODE END I2C3_Init 0 */ /* USER CODE END I2C1_Init 0 */
/* USER CODE BEGIN I2C3_Init 1 */ /* USER CODE BEGIN I2C1_Init 1 */
/* USER CODE END I2C3_Init 1 */ /* USER CODE END I2C1_Init 1 */
hi2c3.Instance = I2C3; hi2c1.Instance = I2C1;
hi2c3.Init.Timing = 0x60505F8C; hi2c1.Init.Timing = 0x6050DCFF;
hi2c3.Init.OwnAddress1 = 0; hi2c1.Init.OwnAddress1 = 0;
hi2c3.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c3.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c3.Init.OwnAddress2 = 0; hi2c1.Init.OwnAddress2 = 0;
hi2c3.Init.OwnAddress2Masks = I2C_OA2_NOMASK; hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c3.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c3.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c3) != HAL_OK) if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{ {
Error_Handler(); Error_Handler();
} }
/** Configure Analogue filter /** Configure Analogue filter
*/ */
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c3, I2C_ANALOGFILTER_ENABLE) != HAL_OK) if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{ {
Error_Handler(); Error_Handler();
} }
/** Configure Digital filter /** Configure Digital filter
*/ */
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c3, 0) != HAL_OK) if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK)
{ {
Error_Handler(); Error_Handler();
} }
/* USER CODE BEGIN I2C3_Init 2 */ /* USER CODE BEGIN I2C1_Init 2 */
/* USER CODE END I2C3_Init 2 */ /* USER CODE END I2C1_Init 2 */
} }
@ -75,63 +75,67 @@ void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle)
GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(i2cHandle->Instance==I2C3) if(i2cHandle->Instance==I2C1)
{ {
/* USER CODE BEGIN I2C3_MspInit 0 */ /* USER CODE BEGIN I2C1_MspInit 0 */
/* USER CODE END I2C3_MspInit 0 */ /* USER CODE END I2C1_MspInit 0 */
/** Initializes the peripherals clocks /** Initializes the peripherals clocks
*/ */
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C3; PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C1;
PeriphClkInit.I2c3ClockSelection = RCC_I2C3CLKSOURCE_PCLK1; PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{ {
Error_Handler(); Error_Handler();
} }
__HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE();
/**I2C3 GPIO Configuration /**I2C1 GPIO Configuration
PC8 ------> I2C3_SCL PB8-BOOT0 ------> I2C1_SCL
PC9 ------> I2C3_SDA PB9 ------> I2C1_SDA
*/ */
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9; GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF8_I2C3; GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* I2C3 clock enable */ __HAL_SYSCFG_FASTMODEPLUS_ENABLE(SYSCFG_FASTMODEPLUS_PB8);
__HAL_RCC_I2C3_CLK_ENABLE();
/* USER CODE BEGIN I2C3_MspInit 1 */
/* USER CODE END I2C3_MspInit 1 */ __HAL_SYSCFG_FASTMODEPLUS_ENABLE(SYSCFG_FASTMODEPLUS_PB9);
/* I2C1 clock enable */
__HAL_RCC_I2C1_CLK_ENABLE();
/* USER CODE BEGIN I2C1_MspInit 1 */
/* USER CODE END I2C1_MspInit 1 */
} }
} }
void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle) void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle)
{ {
if(i2cHandle->Instance==I2C3) if(i2cHandle->Instance==I2C1)
{ {
/* USER CODE BEGIN I2C3_MspDeInit 0 */ /* USER CODE BEGIN I2C1_MspDeInit 0 */
/* USER CODE END I2C3_MspDeInit 0 */ /* USER CODE END I2C1_MspDeInit 0 */
/* Peripheral clock disable */ /* Peripheral clock disable */
__HAL_RCC_I2C3_CLK_DISABLE(); __HAL_RCC_I2C1_CLK_DISABLE();
/**I2C3 GPIO Configuration /**I2C1 GPIO Configuration
PC8 ------> I2C3_SCL PB8-BOOT0 ------> I2C1_SCL
PC9 ------> I2C3_SDA PB9 ------> I2C1_SDA
*/ */
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_8); HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8);
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_9); HAL_GPIO_DeInit(GPIOB, GPIO_PIN_9);
/* USER CODE BEGIN I2C3_MspDeInit 1 */ /* USER CODE BEGIN I2C1_MspDeInit 1 */
/* USER CODE END I2C3_MspDeInit 1 */ /* USER CODE END I2C1_MspDeInit 1 */
} }
} }

View File

@ -20,16 +20,28 @@
#include "main.h" #include "main.h"
#include "adc.h" #include "adc.h"
#include "dma.h" #include "dma.h"
#include "gpio.h"
#include "i2c.h" #include "i2c.h"
#include "opamp.h" #include "opamp.h"
#include "spi.h" #include "spi.h"
#include "tim.h" #include "tim.h"
#include "usb_device.h" #include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/ /* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */ /* USER CODE BEGIN Includes */
#include "APP_Main.h" #include "APP_Main.h"
#include "APP_Task.h"
#include "PreDrive.h"
#include "controller.h"
#include "encoder.h"
#include "foc.h"
#include "pwm_curr.h"
#include "string.h"
#include "usr_config.h"
#include "eeprom.h"
#include "rgb.h"
/* USER CODE END Includes */ /* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/
@ -39,7 +51,9 @@
/* Private define ------------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */ /* USER CODE BEGIN PD */
#define AT24C256_Write 0xA0
#define AT24C256_Read 0xA1
#define BufferSize 256
/* USER CODE END PD */ /* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/
@ -50,7 +64,8 @@
/* Private variables ---------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */ /* USER CODE BEGIN PV */
uint8_t w[BufferSize], r[BufferSize];
uint16_t i, j;
/* USER CODE END PV */ /* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/
@ -94,15 +109,57 @@ int main(void) {
MX_DMA_Init(); MX_DMA_Init();
MX_TIM1_Init(); MX_TIM1_Init();
MX_ADC1_Init(); MX_ADC1_Init();
MX_I2C3_Init();
MX_OPAMP1_Init(); MX_OPAMP1_Init();
MX_OPAMP2_Init(); MX_OPAMP2_Init();
MX_OPAMP3_Init(); MX_OPAMP3_Init();
MX_ADC2_Init(); MX_ADC2_Init();
MX_SPI1_Init(); MX_SPI1_Init();
MX_USB_Device_Init(); MX_USART1_UART_Init();
MX_I2C1_Init();
MX_TIM8_Init();
/* USER CODE BEGIN 2 */ /* USER CODE BEGIN 2 */
HAL_Delay(100);
APP_Init(); APP_Init();
HAL_Delay(100);
// typedef struct
// {
// uint32_t Speed;
// char *st;
// uint8_t TxBuff[16];
// } SystemPrm;
//
// SystemPrm *systemSave;
//
// uint8_t size = 0;
// size = sizeof(SystemPrm);
// for (uint32_t t = 0; t < size; t++) {
// if (EP24C_WriteOneByte(t, *(uint8_t *) systemSave)) {
// printf("Write Successful\r\n");
// }
// ++systemSave;
// }
// uint8_t strOut[size];
// if (EP24C_ReadBytes(0, strOut, size) == HAL_OK) {
// printf("%s\r\n", strOut);
// }
// printf("%u\r\n", sizeof(tEEPROM_storage));
// if (EP24C_WriteLongData(0, (unsigned char *) &e2_memory, sizeof(tEEPROM_storage)) == HAL_OK) {
// printf("Write Successful\r\n");
// }
// HAL_Delay(1000);
// // uint8_t strIn[] = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDDEEEEEEEEFFFFFFFFGGGGGGGGHHHHHHHHI";
// // if (EP24C_WriteLongData(0, strIn, sizeof(strIn)) == HAL_OK) {
// // printf("Write Successful\r\n");
// // }
// // HAL_Delay(100);
// uint8_t strOut[16];
// if (EP24C_ReadBytes(0, strOut, 16) == HAL_OK) {
// printf("%s\r\n", strOut);
// }
/* USER CODE END 2 */ /* USER CODE END 2 */
/* Infinite loop */ /* Infinite loop */
@ -111,7 +168,7 @@ int main(void) {
/* USER CODE END WHILE */ /* USER CODE END WHILE */
/* USER CODE BEGIN 3 */ /* USER CODE BEGIN 3 */
APP_Main(); // APP_Main();
} }
/* USER CODE END 3 */ /* USER CODE END 3 */
} }
@ -125,15 +182,14 @@ void SystemClock_Config(void) {
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage /** Configure the main internal regulator output voltage
*/ */
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST); HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);
/** Initializes the RCC Oscillators according to the specified parameters /** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure. * in the RCC_OscInitTypeDef structure.
*/ */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48 | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2; RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
@ -146,9 +202,8 @@ void SystemClock_Config(void) {
} }
/** Initializes the CPU, AHB and APB buses clocks /** Initializes the CPU, AHB and APB buses clocks
*/ */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
@ -159,12 +214,14 @@ void SystemClock_Config(void) {
} }
/** Enables the Clock Security System /** Enables the Clock Security System
*/ */
HAL_RCC_EnableCSS(); HAL_RCC_EnableCSS();
} }
/* USER CODE BEGIN 4 */ /* USER CODE BEGIN 4 */
//void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
//
//}
/* USER CODE END 4 */ /* USER CODE END 4 */
/** /**
@ -180,7 +237,7 @@ void Error_Handler(void) {
/* USER CODE END Error_Handler_Debug */ /* USER CODE END Error_Handler_Debug */
} }
#ifdef USE_FULL_ASSERT #ifdef USE_FULL_ASSERT
/** /**
* @brief Reports the name of the source file and the source line number * @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred. * where the assert_param error has occurred.
@ -188,11 +245,10 @@ void Error_Handler(void) {
* @param line: assert_param error line source number * @param line: assert_param error line source number
* @retval None * @retval None
*/ */
void assert_failed(uint8_t *file, uint32_t line) void assert_failed(uint8_t *file, uint32_t line) {
{ /* USER CODE BEGIN 6 */
/* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number,
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */ /* USER CODE END 6 */
} }
#endif /* USE_FULL_ASSERT */ #endif /* USE_FULL_ASSERT */

View File

@ -70,7 +70,7 @@ void MX_OPAMP2_Init(void)
hopamp2.Instance = OPAMP2; hopamp2.Instance = OPAMP2;
hopamp2.Init.PowerMode = OPAMP_POWERMODE_NORMALSPEED; hopamp2.Init.PowerMode = OPAMP_POWERMODE_NORMALSPEED;
hopamp2.Init.Mode = OPAMP_STANDALONE_MODE; hopamp2.Init.Mode = OPAMP_STANDALONE_MODE;
hopamp2.Init.InvertingInput = OPAMP_INVERTINGINPUT_IO1; hopamp2.Init.InvertingInput = OPAMP_INVERTINGINPUT_IO0;
hopamp2.Init.NonInvertingInput = OPAMP_NONINVERTINGINPUT_IO0; hopamp2.Init.NonInvertingInput = OPAMP_NONINVERTINGINPUT_IO0;
hopamp2.Init.InternalOutput = DISABLE; hopamp2.Init.InternalOutput = DISABLE;
hopamp2.Init.TimerControlledMuxmode = OPAMP_TIMERCONTROLLEDMUXMODE_DISABLE; hopamp2.Init.TimerControlledMuxmode = OPAMP_TIMERCONTROLLEDMUXMODE_DISABLE;
@ -145,22 +145,16 @@ void HAL_OPAMP_MspInit(OPAMP_HandleTypeDef* opampHandle)
/* USER CODE END OPAMP2_MspInit 0 */ /* USER CODE END OPAMP2_MspInit 0 */
__HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
/**OPAMP2 GPIO Configuration /**OPAMP2 GPIO Configuration
PA5 ------> OPAMP2_VINM
PA6 ------> OPAMP2_VOUT PA6 ------> OPAMP2_VOUT
PA7 ------> OPAMP2_VINP PA7 ------> OPAMP2_VINP
PC5 ------> OPAMP2_VINM
*/ */
GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7; GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/* USER CODE BEGIN OPAMP2_MspInit 1 */ /* USER CODE BEGIN OPAMP2_MspInit 1 */
/* USER CODE END OPAMP2_MspInit 1 */ /* USER CODE END OPAMP2_MspInit 1 */
@ -215,13 +209,11 @@ void HAL_OPAMP_MspDeInit(OPAMP_HandleTypeDef* opampHandle)
/* USER CODE END OPAMP2_MspDeInit 0 */ /* USER CODE END OPAMP2_MspDeInit 0 */
/**OPAMP2 GPIO Configuration /**OPAMP2 GPIO Configuration
PA5 ------> OPAMP2_VINM
PA6 ------> OPAMP2_VOUT PA6 ------> OPAMP2_VOUT
PA7 ------> OPAMP2_VINP PA7 ------> OPAMP2_VINP
PC5 ------> OPAMP2_VINM
*/ */
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_6|GPIO_PIN_7); HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7);
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_5);
/* USER CODE BEGIN OPAMP2_MspDeInit 1 */ /* USER CODE BEGIN OPAMP2_MspDeInit 1 */

View File

@ -44,7 +44,7 @@ void MX_SPI1_Init(void)
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH; hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE; hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;

View File

@ -22,7 +22,12 @@
#include "stm32g4xx_it.h" #include "stm32g4xx_it.h"
/* Private includes ----------------------------------------------------------*/ /* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */ /* USER CODE BEGIN Includes */
#include "APP_Main.h"
#include "APP_Task.h" #include "APP_Task.h"
#include "controller.h"
#include "string.h"
#include "usart.h"
#include "usr_config.h"
/* USER CODE END Includes */ /* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/
@ -56,11 +61,14 @@
/* USER CODE END 0 */ /* USER CODE END 0 */
/* External variables --------------------------------------------------------*/ /* External variables --------------------------------------------------------*/
extern PCD_HandleTypeDef hpcd_USB_FS;
extern DMA_HandleTypeDef hdma_adc1; extern DMA_HandleTypeDef hdma_adc1;
extern ADC_HandleTypeDef hadc1; extern ADC_HandleTypeDef hadc1;
extern ADC_HandleTypeDef hadc2; extern ADC_HandleTypeDef hadc2;
extern DMA_HandleTypeDef hdma_tim8_ch1;
extern TIM_HandleTypeDef htim1; extern TIM_HandleTypeDef htim1;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */ /* USER CODE BEGIN EV */
/* USER CODE END EV */ /* USER CODE END EV */
@ -71,116 +79,129 @@ extern TIM_HandleTypeDef htim1;
/** /**
* @brief This function handles Non maskable interrupt. * @brief This function handles Non maskable interrupt.
*/ */
void NMI_Handler(void) { void NMI_Handler(void)
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */ {
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */
HAL_RCC_NMI_IRQHandler(); HAL_RCC_NMI_IRQHandler();
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1) { while (1) {
} }
/* USER CODE END NonMaskableInt_IRQn 1 */ /* USER CODE END NonMaskableInt_IRQn 1 */
} }
/** /**
* @brief This function handles Hard fault interrupt. * @brief This function handles Hard fault interrupt.
*/ */
void HardFault_Handler(void) { void HardFault_Handler(void)
/* USER CODE BEGIN HardFault_IRQn 0 */ {
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */
while (1) { while (1)
/* USER CODE BEGIN W1_HardFault_IRQn 0 */ {
/* USER CODE END W1_HardFault_IRQn 0 */ /* USER CODE BEGIN W1_HardFault_IRQn 0 */
} /* USER CODE END W1_HardFault_IRQn 0 */
}
} }
/** /**
* @brief This function handles Memory management fault. * @brief This function handles Memory management fault.
*/ */
void MemManage_Handler(void) { void MemManage_Handler(void)
/* USER CODE BEGIN MemoryManagement_IRQn 0 */ {
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */
while (1) { while (1)
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ {
/* USER CODE END W1_MemoryManagement_IRQn 0 */ /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
} /* USER CODE END W1_MemoryManagement_IRQn 0 */
}
} }
/** /**
* @brief This function handles Prefetch fault, memory access fault. * @brief This function handles Prefetch fault, memory access fault.
*/ */
void BusFault_Handler(void) { void BusFault_Handler(void)
/* USER CODE BEGIN BusFault_IRQn 0 */ {
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */
while (1) { while (1)
/* USER CODE BEGIN W1_BusFault_IRQn 0 */ {
/* USER CODE END W1_BusFault_IRQn 0 */ /* USER CODE BEGIN W1_BusFault_IRQn 0 */
} /* USER CODE END W1_BusFault_IRQn 0 */
}
} }
/** /**
* @brief This function handles Undefined instruction or illegal state. * @brief This function handles Undefined instruction or illegal state.
*/ */
void UsageFault_Handler(void) { void UsageFault_Handler(void)
/* USER CODE BEGIN UsageFault_IRQn 0 */ {
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */
while (1) { while (1)
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */ {
/* USER CODE END W1_UsageFault_IRQn 0 */ /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
} /* USER CODE END W1_UsageFault_IRQn 0 */
}
} }
/** /**
* @brief This function handles System service call via SWI instruction. * @brief This function handles System service call via SWI instruction.
*/ */
void SVC_Handler(void) { void SVC_Handler(void)
/* USER CODE BEGIN SVCall_IRQn 0 */ {
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */
} }
/** /**
* @brief This function handles Debug monitor. * @brief This function handles Debug monitor.
*/ */
void DebugMon_Handler(void) { void DebugMon_Handler(void)
/* USER CODE BEGIN DebugMonitor_IRQn 0 */ {
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */
} }
/** /**
* @brief This function handles Pendable request for system service. * @brief This function handles Pendable request for system service.
*/ */
void PendSV_Handler(void) { void PendSV_Handler(void)
/* USER CODE BEGIN PendSV_IRQn 0 */ {
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */
} }
/** /**
* @brief This function handles System tick timer. * @brief This function handles System tick timer.
*/ */
void SysTick_Handler(void) { void SysTick_Handler(void)
/* USER CODE BEGIN SysTick_IRQn 0 */ {
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */
HAL_IncTick(); HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */
} }
/******************************************************************************/ /******************************************************************************/
@ -193,54 +214,106 @@ void SysTick_Handler(void) {
/** /**
* @brief This function handles DMA1 channel1 global interrupt. * @brief This function handles DMA1 channel1 global interrupt.
*/ */
void DMA1_Channel1_IRQHandler(void) { void DMA1_Channel1_IRQHandler(void)
/* USER CODE BEGIN DMA1_Channel1_IRQn 0 */ {
/* USER CODE BEGIN DMA1_Channel1_IRQn 0 */
/* USER CODE END DMA1_Channel1_IRQn 0 */ /* USER CODE END DMA1_Channel1_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_adc1); HAL_DMA_IRQHandler(&hdma_adc1);
/* USER CODE BEGIN DMA1_Channel1_IRQn 1 */ /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */
/* USER CODE END DMA1_Channel1_IRQn 1 */ /* USER CODE END DMA1_Channel1_IRQn 1 */
}
/**
* @brief This function handles DMA1 channel6 global interrupt.
*/
void DMA1_Channel6_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel6_IRQn 0 */
/* USER CODE END DMA1_Channel6_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_tim8_ch1);
/* USER CODE BEGIN DMA1_Channel6_IRQn 1 */
/* USER CODE END DMA1_Channel6_IRQn 1 */
} }
/** /**
* @brief This function handles ADC1 and ADC2 global interrupt. * @brief This function handles ADC1 and ADC2 global interrupt.
*/ */
void ADC1_2_IRQHandler(void) { void ADC1_2_IRQHandler(void)
/* USER CODE BEGIN ADC1_2_IRQn 0 */ {
/* USER CODE BEGIN ADC1_2_IRQn 0 */
/* USER CODE END ADC1_2_IRQn 0 */ /* USER CODE END ADC1_2_IRQn 0 */
HAL_ADC_IRQHandler(&hadc1); HAL_ADC_IRQHandler(&hadc1);
HAL_ADC_IRQHandler(&hadc2); HAL_ADC_IRQHandler(&hadc2);
/* USER CODE BEGIN ADC1_2_IRQn 1 */ /* USER CODE BEGIN ADC1_2_IRQn 1 */
High_Frequency_Task(); // MCT_high_frequency_task();
/* USER CODE END ADC1_2_IRQn 1 */ // printf("ADC1_2_IRQHandler\r\n");
} /* USER CODE END ADC1_2_IRQn 1 */
/**
* @brief This function handles USB low priority interrupt remap.
*/
void USB_LP_IRQHandler(void) {
/* USER CODE BEGIN USB_LP_IRQn 0 */
/* USER CODE END USB_LP_IRQn 0 */
HAL_PCD_IRQHandler(&hpcd_USB_FS);
/* USER CODE BEGIN USB_LP_IRQn 1 */
/* USER CODE END USB_LP_IRQn 1 */
} }
/** /**
* @brief This function handles TIM1 update interrupt and TIM16 global interrupt. * @brief This function handles TIM1 update interrupt and TIM16 global interrupt.
*/ */
void TIM1_UP_TIM16_IRQHandler(void) { void TIM1_UP_TIM16_IRQHandler(void)
/* USER CODE BEGIN TIM1_UP_TIM16_IRQn 0 */ {
/* USER CODE BEGIN TIM1_UP_TIM16_IRQn 0 */
/* USER CODE END TIM1_UP_TIM16_IRQn 0 */ /* USER CODE END TIM1_UP_TIM16_IRQn 0 */
HAL_TIM_IRQHandler(&htim1); HAL_TIM_IRQHandler(&htim1);
/* USER CODE BEGIN TIM1_UP_TIM16_IRQn 1 */ /* USER CODE BEGIN TIM1_UP_TIM16_IRQn 1 */
MCT_safety_task();
/* USER CODE END TIM1_UP_TIM16_IRQn 1 */
}
/* USER CODE END TIM1_UP_TIM16_IRQn 1 */ /**
* @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
USER_UART_IRQHandler(&huart1);
// USART1_IRQHandler_Status = 1;
// __HAL_UART_CLEAR_IDLEFLAG(&huart1);//清除标志�???????
// // printf("%s\r\n", RxBuffer);
// HAL_UART_Receive_DMA(&huart1, RxBuffer, 2);//é‡<C3A9>æ°æ‰“å¼€DMA与IDLE接收
/* USER CODE END USART1_IRQn 1 */
}
/**
* @brief This function handles DMA2 channel1 global interrupt.
*/
void DMA2_Channel1_IRQHandler(void)
{
/* USER CODE BEGIN DMA2_Channel1_IRQn 0 */
/* USER CODE END DMA2_Channel1_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart1_rx);
/* USER CODE BEGIN DMA2_Channel1_IRQn 1 */
/* USER CODE END DMA2_Channel1_IRQn 1 */
}
/**
* @brief This function handles DMA2 channel2 global interrupt.
*/
void DMA2_Channel2_IRQHandler(void)
{
/* USER CODE BEGIN DMA2_Channel2_IRQn 0 */
/* USER CODE END DMA2_Channel2_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart1_tx);
/* USER CODE BEGIN DMA2_Channel2_IRQn 1 */
/* USER CODE END DMA2_Channel2_IRQn 1 */
} }
/* USER CODE BEGIN 1 */ /* USER CODE BEGIN 1 */

View File

@ -25,6 +25,8 @@
/* USER CODE END 0 */ /* USER CODE END 0 */
TIM_HandleTypeDef htim1; TIM_HandleTypeDef htim1;
TIM_HandleTypeDef htim8;
DMA_HandleTypeDef hdma_tim8_ch1;
/* TIM1 init function */ /* TIM1 init function */
void MX_TIM1_Init(void) void MX_TIM1_Init(void)
@ -116,6 +118,83 @@ void MX_TIM1_Init(void)
/* USER CODE END TIM1_Init 2 */ /* USER CODE END TIM1_Init 2 */
HAL_TIM_MspPostInit(&htim1); HAL_TIM_MspPostInit(&htim1);
}
/* TIM8 init function */
void MX_TIM8_Init(void)
{
/* USER CODE BEGIN TIM8_Init 0 */
/* USER CODE END TIM8_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
/* USER CODE BEGIN TIM8_Init 1 */
/* USER CODE END TIM8_Init 1 */
htim8.Instance = TIM8;
htim8.Init.Prescaler = 0;
htim8.Init.CounterMode = TIM_COUNTERMODE_UP;
htim8.Init.Period = 209;
htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim8.Init.RepetitionCounter = 0;
htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim8) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim8, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim8) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterOutputTrigger2 = TIM_TRGO2_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim8, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.BreakFilter = 0;
sBreakDeadTimeConfig.BreakAFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.Break2State = TIM_BREAK2_DISABLE;
sBreakDeadTimeConfig.Break2Polarity = TIM_BREAK2POLARITY_HIGH;
sBreakDeadTimeConfig.Break2Filter = 0;
sBreakDeadTimeConfig.Break2AFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim8, &sBreakDeadTimeConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM8_Init 2 */
/* USER CODE END TIM8_Init 2 */
HAL_TIM_MspPostInit(&htim8);
} }
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle) void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
@ -130,12 +209,42 @@ void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
__HAL_RCC_TIM1_CLK_ENABLE(); __HAL_RCC_TIM1_CLK_ENABLE();
/* TIM1 interrupt Init */ /* TIM1 interrupt Init */
HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, 15, 0); HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn); HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn);
/* USER CODE BEGIN TIM1_MspInit 1 */ /* USER CODE BEGIN TIM1_MspInit 1 */
/* USER CODE END TIM1_MspInit 1 */ /* USER CODE END TIM1_MspInit 1 */
} }
else if(tim_baseHandle->Instance==TIM8)
{
/* USER CODE BEGIN TIM8_MspInit 0 */
/* USER CODE END TIM8_MspInit 0 */
/* TIM8 clock enable */
__HAL_RCC_TIM8_CLK_ENABLE();
/* TIM8 DMA Init */
/* TIM8_CH1 Init */
hdma_tim8_ch1.Instance = DMA1_Channel6;
hdma_tim8_ch1.Init.Request = DMA_REQUEST_TIM8_CH1;
hdma_tim8_ch1.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_tim8_ch1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_tim8_ch1.Init.MemInc = DMA_MINC_ENABLE;
hdma_tim8_ch1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_tim8_ch1.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_tim8_ch1.Init.Mode = DMA_CIRCULAR;
hdma_tim8_ch1.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_tim8_ch1) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(tim_baseHandle,hdma[TIM_DMA_ID_CC1],hdma_tim8_ch1);
/* USER CODE BEGIN TIM8_MspInit 1 */
/* USER CODE END TIM8_MspInit 1 */
}
} }
void HAL_TIM_MspPostInit(TIM_HandleTypeDef* timHandle) void HAL_TIM_MspPostInit(TIM_HandleTypeDef* timHandle)
{ {
@ -146,28 +255,62 @@ void HAL_TIM_MspPostInit(TIM_HandleTypeDef* timHandle)
/* USER CODE BEGIN TIM1_MspPostInit 0 */ /* USER CODE BEGIN TIM1_MspPostInit 0 */
/* USER CODE END TIM1_MspPostInit 0 */ /* USER CODE END TIM1_MspPostInit 0 */
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE();
/**TIM1 GPIO Configuration /**TIM1 GPIO Configuration
PE8 ------> TIM1_CH1N PB13 ------> TIM1_CH1N
PE9 ------> TIM1_CH1 PB14 ------> TIM1_CH2N
PE10 ------> TIM1_CH2N PB15 ------> TIM1_CH3N
PE11 ------> TIM1_CH2 PA8 ------> TIM1_CH1
PE12 ------> TIM1_CH3N PA9 ------> TIM1_CH2
PE13 ------> TIM1_CH3 PA10 ------> TIM1_CH3
*/ */
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11 GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14;
|GPIO_PIN_12|GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM1; GPIO_InitStruct.Alternate = GPIO_AF6_TIM1;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF4_TIM1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_TIM1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USER CODE BEGIN TIM1_MspPostInit 1 */ /* USER CODE BEGIN TIM1_MspPostInit 1 */
/* USER CODE END TIM1_MspPostInit 1 */ /* USER CODE END TIM1_MspPostInit 1 */
} }
else if(timHandle->Instance==TIM8)
{
/* USER CODE BEGIN TIM8_MspPostInit 0 */
/* USER CODE END TIM8_MspPostInit 0 */
__HAL_RCC_GPIOC_CLK_ENABLE();
/**TIM8 GPIO Configuration
PC6 ------> TIM8_CH1
*/
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF4_TIM8;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/* USER CODE BEGIN TIM8_MspPostInit 1 */
/* USER CODE END TIM8_MspPostInit 1 */
}
} }
@ -188,6 +331,20 @@ void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
/* USER CODE END TIM1_MspDeInit 1 */ /* USER CODE END TIM1_MspDeInit 1 */
} }
else if(tim_baseHandle->Instance==TIM8)
{
/* USER CODE BEGIN TIM8_MspDeInit 0 */
/* USER CODE END TIM8_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM8_CLK_DISABLE();
/* TIM8 DMA DeInit */
HAL_DMA_DeInit(tim_baseHandle->hdma[TIM_DMA_ID_CC1]);
/* USER CODE BEGIN TIM8_MspDeInit 1 */
/* USER CODE END TIM8_MspDeInit 1 */
}
} }
/* USER CODE BEGIN 1 */ /* USER CODE BEGIN 1 */

File diff suppressed because it is too large Load Diff

View File

@ -1,88 +0,0 @@
/**
******************************************************************************
* @file stm32g4xx_hal_pcd_ex.h
* @author MCD Application Team
* @brief Header file of PCD HAL Extension module.
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32G4xx_HAL_PCD_EX_H
#define STM32G4xx_HAL_PCD_EX_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal_def.h"
#if defined (USB)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @addtogroup PCDEx
* @{
*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macros -----------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup PCDEx_Exported_Functions PCDEx Exported Functions
* @{
*/
/** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions
* @{
*/
HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr,
uint16_t ep_kind, uint32_t pmaadress);
HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd);
HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd);
HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd);
HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd);
void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd);
void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg);
void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* STM32G4xx_HAL_PCD_EX_H */

View File

@ -1,239 +0,0 @@
/**
******************************************************************************
* @file stm32g4xx_ll_usb.h
* @author MCD Application Team
* @brief Header file of USB Low Layer HAL module.
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32G4xx_LL_USB_H
#define STM32G4xx_LL_USB_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal_def.h"
#if defined (USB)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @addtogroup USB_LL
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief USB Mode definition
*/
typedef enum
{
USB_DEVICE_MODE = 0
} USB_ModeTypeDef;
/**
* @brief USB Initialization Structure definition
*/
typedef struct
{
uint32_t dev_endpoints; /*!< Device Endpoints number.
This parameter depends on the used USB core.
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint32_t speed; /*!< USB Core speed.
This parameter can be any value of @ref PCD_Speed/HCD_Speed
(HCD_SPEED_xxx, HCD_SPEED_xxx) */
uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */
uint32_t phy_itface; /*!< Select the used PHY interface.
This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */
uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */
uint32_t low_power_enable; /*!< Enable or disable Low Power mode */
uint32_t lpm_enable; /*!< Enable or disable Battery charging. */
uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */
} USB_CfgTypeDef;
typedef struct
{
uint8_t num; /*!< Endpoint number
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint8_t is_in; /*!< Endpoint direction
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t is_stall; /*!< Endpoint stall condition
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t type; /*!< Endpoint type
This parameter can be any value of @ref USB_EP_Type */
uint8_t data_pid_start; /*!< Initial data PID
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint16_t pmaadress; /*!< PMA Address
This parameter can be any value between Min_addr = 0 and Max_addr = 1K */
uint16_t pmaaddr0; /*!< PMA Address0
This parameter can be any value between Min_addr = 0 and Max_addr = 1K */
uint16_t pmaaddr1; /*!< PMA Address1
This parameter can be any value between Min_addr = 0 and Max_addr = 1K */
uint8_t doublebuffer; /*!< Double buffer enable
This parameter can be 0 or 1 */
uint16_t tx_fifo_num; /*!< This parameter is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral
This parameter is added to ensure compatibility across USB peripherals */
uint32_t maxpacket; /*!< Endpoint Max packet size
This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */
uint8_t *xfer_buff; /*!< Pointer to transfer buffer */
uint32_t xfer_len; /*!< Current transfer length */
uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */
uint32_t xfer_len_db; /*!< double buffer transfer length used with bulk double buffer in */
uint8_t xfer_fill_db; /*!< double buffer Need to Fill new buffer used with bulk_in */
} USB_EPTypeDef;
/* Exported constants --------------------------------------------------------*/
/** @defgroup PCD_Exported_Constants PCD Exported Constants
* @{
*/
/** @defgroup USB_LL_EP0_MPS USB Low Layer EP0 MPS
* @{
*/
#define EP_MPS_64 0U
#define EP_MPS_32 1U
#define EP_MPS_16 2U
#define EP_MPS_8 3U
/**
* @}
*/
/** @defgroup USB_LL_EP_Type USB Low Layer EP Type
* @{
*/
#define EP_TYPE_CTRL 0U
#define EP_TYPE_ISOC 1U
#define EP_TYPE_BULK 2U
#define EP_TYPE_INTR 3U
#define EP_TYPE_MSK 3U
/**
* @}
*/
/** @defgroup USB_LL Device Speed
* @{
*/
#define USBD_FS_SPEED 2U
/**
* @}
*/
#define BTABLE_ADDRESS 0x000U
#define PMA_ACCESS 1U
#define EP_ADDR_MSK 0x7U
#ifndef USE_USB_DOUBLE_BUFFER
#define USE_USB_DOUBLE_BUFFER 1U
#endif /* USE_USB_DOUBLE_BUFFER */
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USB_LL_Exported_Functions USB Low Layer Exported Functions
* @{
*/
HAL_StatusTypeDef USB_CoreInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg);
HAL_StatusTypeDef USB_DevInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg);
HAL_StatusTypeDef USB_EnableGlobalInt(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_DisableGlobalInt(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx, USB_ModeTypeDef mode);
#if defined (HAL_PCD_MODULE_ENABLED)
HAL_StatusTypeDef USB_ActivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep);
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep);
HAL_StatusTypeDef USB_EPStartXfer(USB_TypeDef *USBx, USB_EPTypeDef *ep);
HAL_StatusTypeDef USB_EPSetStall(USB_TypeDef *USBx, USB_EPTypeDef *ep);
HAL_StatusTypeDef USB_EPClearStall(USB_TypeDef *USBx, USB_EPTypeDef *ep);
#endif /* defined (HAL_PCD_MODULE_ENABLED) */
HAL_StatusTypeDef USB_SetDevAddress(USB_TypeDef *USBx, uint8_t address);
HAL_StatusTypeDef USB_DevConnect(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_DevDisconnect(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_StopDevice(USB_TypeDef *USBx);
uint32_t USB_ReadInterrupts(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_TypeDef *USBx);
HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_TypeDef *USBx);
void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf,
uint16_t wPMABufAddr, uint16_t wNBytes);
void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf,
uint16_t wPMABufAddr, uint16_t wNBytes);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* STM32G4xx_LL_USB_H */

File diff suppressed because it is too large Load Diff

View File

@ -1,335 +0,0 @@
/**
******************************************************************************
* @file stm32g4xx_hal_pcd_ex.c
* @author MCD Application Team
* @brief PCD Extended HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Extended features functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup PCDEx PCDEx
* @brief PCD Extended HAL module driver
* @{
*/
#ifdef HAL_PCD_MODULE_ENABLED
#if defined (USB)
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions
* @{
*/
/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions
* @brief PCDEx control functions
*
@verbatim
===============================================================================
##### Extended features functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Update FIFO configuration
@endverbatim
* @{
*/
/**
* @brief Configure PMA for EP
* @param hpcd Device instance
* @param ep_addr endpoint address
* @param ep_kind endpoint Kind
* USB_SNG_BUF: Single Buffer used
* USB_DBL_BUF: Double Buffer used
* @param pmaadress: EP address in The PMA: In case of single buffer endpoint
* this parameter is 16-bit value providing the address
* in PMA allocated to endpoint.
* In case of double buffer endpoint this parameter
* is a 32-bit value providing the endpoint buffer 0 address
* in the LSB part of 32-bit value and endpoint buffer 1 address
* in the MSB part of 32-bit value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr,
uint16_t ep_kind, uint32_t pmaadress)
{
PCD_EPTypeDef *ep;
/* initialize ep structure*/
if ((0x80U & ep_addr) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
}
else
{
ep = &hpcd->OUT_ep[ep_addr];
}
/* Here we check if the endpoint is single or double Buffer*/
if (ep_kind == PCD_SNG_BUF)
{
/* Single Buffer */
ep->doublebuffer = 0U;
/* Configure the PMA */
ep->pmaadress = (uint16_t)pmaadress;
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else /* USB_DBL_BUF */
{
/* Double Buffer Endpoint */
ep->doublebuffer = 1U;
/* Configure the PMA */
ep->pmaaddr0 = (uint16_t)(pmaadress & 0xFFFFU);
ep->pmaaddr1 = (uint16_t)((pmaadress & 0xFFFF0000U) >> 16);
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return HAL_OK;
}
/**
* @brief Activate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 1U;
/* Enable BCD feature */
USBx->BCDR |= USB_BCDR_BCDEN;
/* Enable DCD : Data Contact Detect */
USBx->BCDR &= ~(USB_BCDR_PDEN);
USBx->BCDR &= ~(USB_BCDR_SDEN);
USBx->BCDR |= USB_BCDR_DCDEN;
return HAL_OK;
}
/**
* @brief Deactivate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 0U;
/* Disable BCD feature */
USBx->BCDR &= ~(USB_BCDR_BCDEN);
return HAL_OK;
}
/**
* @brief Handle BatteryCharging Process.
* @param hpcd PCD handle
* @retval HAL status
*/
void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
uint32_t tickstart = HAL_GetTick();
/* Wait Detect flag or a timeout is happen */
while ((USBx->BCDR & USB_BCDR_DCDET) == 0U)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > 1000U)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_ERROR);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
return;
}
}
HAL_Delay(200U);
/* Data Pin Contact ? Check Detect flag */
if ((USBx->BCDR & USB_BCDR_DCDET) == USB_BCDR_DCDET)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Primary detection: checks if connected to Standard Downstream Port
(without charging capability) */
USBx->BCDR &= ~(USB_BCDR_DCDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_PDEN);
HAL_Delay(50U);
/* If Charger detect ? */
if ((USBx->BCDR & USB_BCDR_PDET) == USB_BCDR_PDET)
{
/* Start secondary detection to check connection to Charging Downstream
Port or Dedicated Charging Port */
USBx->BCDR &= ~(USB_BCDR_PDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_SDEN);
HAL_Delay(50U);
/* If CDP ? */
if ((USBx->BCDR & USB_BCDR_SDET) == USB_BCDR_SDET)
{
/* Dedicated Downstream Port DCP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
/* Charging Downstream Port CDP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
}
else /* NO */
{
/* Standard Downstream Port */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Battery Charging capability discovery finished Start Enumeration */
(void)HAL_PCDEx_DeActivateBCD(hpcd);
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/**
* @brief Activate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 1U;
hpcd->LPM_State = LPM_L0;
USBx->LPMCSR |= USB_LPMCSR_LMPEN;
USBx->LPMCSR |= USB_LPMCSR_LPMACK;
return HAL_OK;
}
/**
* @brief Deactivate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 0U;
USBx->LPMCSR &= ~(USB_LPMCSR_LMPEN);
USBx->LPMCSR &= ~(USB_LPMCSR_LPMACK);
return HAL_OK;
}
/**
* @brief Send LPM message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_LPM_Callback could be implemented in the user file
*/
}
/**
* @brief Send BatteryCharging message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_BCD_Callback could be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#endif /* HAL_PCD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/

View File

@ -1,822 +0,0 @@
/**
******************************************************************************
* @file stm32g4xx_ll_usb.c
* @author MCD Application Team
* @brief USB Low Layer HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Initialization/de-initialization functions
* + I/O operation functions
* + Peripheral Control functions
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
(#) Fill parameters of Init structure in USB_OTG_CfgTypeDef structure.
(#) Call USB_CoreInit() API to initialize the USB Core peripheral.
(#) The upper HAL HCD/PCD driver will call the right routines for its internal processes.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_LL_USB_DRIVER
* @{
*/
#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED)
#if defined (USB)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the USB Core
* @param USBx USB Instance
* @param cfg pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_CoreInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(USBx);
UNUSED(cfg);
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_EnableGlobalInt
* Enables the controller's Global Int in the AHB Config reg
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_EnableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask;
/* Clear pending interrupts */
USBx->ISTR = 0U;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM |
USB_CNTR_SUSPM | USB_CNTR_ERRM |
USB_CNTR_SOFM | USB_CNTR_ESOFM |
USB_CNTR_RESETM | USB_CNTR_L1REQM;
/* Set interrupt mask */
USBx->CNTR = (uint16_t)winterruptmask;
return HAL_OK;
}
/**
* @brief USB_DisableGlobalInt
* Disable the controller's Global Int in the AHB Config reg
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DisableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM |
USB_CNTR_SUSPM | USB_CNTR_ERRM |
USB_CNTR_SOFM | USB_CNTR_ESOFM |
USB_CNTR_RESETM | USB_CNTR_L1REQM;
/* Clear interrupt mask */
USBx->CNTR &= (uint16_t)(~winterruptmask);
return HAL_OK;
}
/**
* @brief USB_SetCurrentMode Set functional mode
* @param USBx Selected device
* @param mode current core mode
* This parameter can be one of the these values:
* @arg USB_DEVICE_MODE Peripheral mode
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx, USB_ModeTypeDef mode)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(USBx);
UNUSED(mode);
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_DevInit Initializes the USB controller registers
* for device mode
* @param USBx Selected device
* @param cfg pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(cfg);
/* Init Device */
/* CNTR_FRES = 1 */
USBx->CNTR = (uint16_t)USB_CNTR_FRES;
/* CNTR_FRES = 0 */
USBx->CNTR = 0U;
/* Clear pending interrupts */
USBx->ISTR = 0U;
/*Set Btable Address*/
USBx->BTABLE = BTABLE_ADDRESS;
return HAL_OK;
}
#if defined (HAL_PCD_MODULE_ENABLED)
/**
* @brief Activate and configure an endpoint
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
HAL_StatusTypeDef ret = HAL_OK;
uint16_t wEpRegVal;
wEpRegVal = PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_T_MASK;
/* initialize Endpoint */
switch (ep->type)
{
case EP_TYPE_CTRL:
wEpRegVal |= USB_EP_CONTROL;
break;
case EP_TYPE_BULK:
wEpRegVal |= USB_EP_BULK;
break;
case EP_TYPE_INTR:
wEpRegVal |= USB_EP_INTERRUPT;
break;
case EP_TYPE_ISOC:
wEpRegVal |= USB_EP_ISOCHRONOUS;
break;
default:
ret = HAL_ERROR;
break;
}
PCD_SET_ENDPOINT(USBx, ep->num, (wEpRegVal | USB_EP_CTR_RX | USB_EP_CTR_TX));
PCD_SET_EP_ADDRESS(USBx, ep->num, ep->num);
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
/*Set the endpoint Transmit buffer address */
PCD_SET_EP_TX_ADDRESS(USBx, ep->num, ep->pmaadress);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
else
{
/* Configure TX Endpoint to disabled state */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
}
else
{
/* Set the endpoint Receive buffer address */
PCD_SET_EP_RX_ADDRESS(USBx, ep->num, ep->pmaadress);
/* Set the endpoint Receive buffer counter */
PCD_SET_EP_RX_CNT(USBx, ep->num, ep->maxpacket);
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure VALID status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/* Double Buffer */
else
{
if (ep->type == EP_TYPE_BULK)
{
/* Set bulk endpoint as double buffered */
PCD_SET_BULK_EP_DBUF(USBx, ep->num);
}
else
{
/* Set the ISOC endpoint in double buffer mode */
PCD_CLEAR_EP_KIND(USBx, ep->num);
}
/* Set buffer address for double buffered mode */
PCD_SET_EP_DBUF_ADDR(USBx, ep->num, ep->pmaaddr0, ep->pmaaddr1);
if (ep->is_in == 0U)
{
/* Clear the data toggle bits for the endpoint IN/OUT */
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT */
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
else
{
/* Configure TX Endpoint to disabled state */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return ret;
}
/**
* @brief De-activate and de-initialize an endpoint
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/* Double Buffer */
else
{
if (ep->is_in == 0U)
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Reset value of the data toggle bits for the endpoint out*/
PCD_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return HAL_OK;
}
/**
* @brief USB_EPStartXfer setup and starts a transfer over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPStartXfer(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
uint32_t len;
#if (USE_USB_DOUBLE_BUFFER == 1U)
uint16_t pmabuffer;
uint16_t wEPVal;
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/* IN endpoint */
if (ep->is_in == 1U)
{
/*Multi packet transfer*/
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
}
else
{
len = ep->xfer_len;
}
/* configure and validate Tx endpoint */
if (ep->doublebuffer == 0U)
{
USB_WritePMA(USBx, ep->xfer_buff, ep->pmaadress, (uint16_t)len);
PCD_SET_EP_TX_CNT(USBx, ep->num, len);
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else
{
/* double buffer bulk management */
if (ep->type == EP_TYPE_BULK)
{
if (ep->xfer_len_db > ep->maxpacket)
{
/* enable double buffer */
PCD_SET_BULK_EP_DBUF(USBx, ep->num);
/* each Time to write in PMA xfer_len_db will */
ep->xfer_len_db -= len;
/* Fill the two first buffer in the Buffer0 & Buffer1 */
if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U)
{
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
ep->xfer_buff += len;
if (ep->xfer_len_db > ep->maxpacket)
{
ep->xfer_len_db -= len;
}
else
{
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
}
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
else
{
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
ep->xfer_buff += len;
if (ep->xfer_len_db > ep->maxpacket)
{
ep->xfer_len_db -= len;
}
else
{
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
}
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
/* auto Switch to single buffer mode when transfer <Mps no need to manage in double buffer */
else
{
len = ep->xfer_len_db;
/* disable double buffer mode for Bulk endpoint */
PCD_CLEAR_BULK_EP_DBUF(USBx, ep->num);
/* Set Tx count with nbre of byte to be transmitted */
PCD_SET_EP_TX_CNT(USBx, ep->num, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
else /* manage isochronous double buffer IN mode */
{
/* each Time to write in PMA xfer_len_db will */
ep->xfer_len_db -= len;
/* Fill the data buffer */
if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U)
{
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
else
{
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_VALID);
}
else /* OUT endpoint */
{
if (ep->doublebuffer == 0U)
{
/* Multi packet transfer */
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len -= len;
}
else
{
len = ep->xfer_len;
ep->xfer_len = 0U;
}
/* configure and validate Rx endpoint */
PCD_SET_EP_RX_CNT(USBx, ep->num, len);
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else
{
/* First Transfer Coming From HAL_PCD_EP_Receive & From ISR */
/* Set the Double buffer counter */
if (ep->type == EP_TYPE_BULK)
{
PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, ep->maxpacket);
/* Coming from ISR */
if (ep->xfer_count != 0U)
{
/* update last value to check if there is blocking state */
wEPVal = PCD_GET_ENDPOINT(USBx, ep->num);
/*Blocking State */
if ((((wEPVal & USB_EP_DTOG_RX) != 0U) && ((wEPVal & USB_EP_DTOG_TX) != 0U)) ||
(((wEPVal & USB_EP_DTOG_RX) == 0U) && ((wEPVal & USB_EP_DTOG_TX) == 0U)))
{
PCD_FREE_USER_BUFFER(USBx, ep->num, 0U);
}
}
}
/* iso out double */
else if (ep->type == EP_TYPE_ISOC)
{
/* Multi packet transfer */
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len -= len;
}
else
{
len = ep->xfer_len;
ep->xfer_len = 0U;
}
PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, len);
}
else
{
return HAL_ERROR;
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
return HAL_OK;
}
/**
* @brief USB_EPSetStall set a stall condition over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPSetStall(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->is_in != 0U)
{
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_STALL);
}
else
{
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_STALL);
}
return HAL_OK;
}
/**
* @brief USB_EPClearStall Clear a stall condition over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPClearStall(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure VALID status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
}
return HAL_OK;
}
#endif /* defined (HAL_PCD_MODULE_ENABLED) */
/**
* @brief USB_StopDevice Stop the usb device mode
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_StopDevice(USB_TypeDef *USBx)
{
/* disable all interrupts and force USB reset */
USBx->CNTR = (uint16_t)USB_CNTR_FRES;
/* clear interrupt status register */
USBx->ISTR = 0U;
/* switch-off device */
USBx->CNTR = (uint16_t)(USB_CNTR_FRES | USB_CNTR_PDWN);
return HAL_OK;
}
/**
* @brief USB_SetDevAddress Stop the usb device mode
* @param USBx Selected device
* @param address new device address to be assigned
* This parameter can be a value from 0 to 255
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetDevAddress(USB_TypeDef *USBx, uint8_t address)
{
if (address == 0U)
{
/* set device address and enable function */
USBx->DADDR = (uint16_t)USB_DADDR_EF;
}
return HAL_OK;
}
/**
* @brief USB_DevConnect Connect the USB device by enabling the pull-up/pull-down
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevConnect(USB_TypeDef *USBx)
{
/* Enabling DP Pull-UP bit to Connect internal PU resistor on USB DP line */
USBx->BCDR |= (uint16_t)USB_BCDR_DPPU;
return HAL_OK;
}
/**
* @brief USB_DevDisconnect Disconnect the USB device by disabling the pull-up/pull-down
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevDisconnect(USB_TypeDef *USBx)
{
/* Disable DP Pull-Up bit to disconnect the Internal PU resistor on USB DP line */
USBx->BCDR &= (uint16_t)(~(USB_BCDR_DPPU));
return HAL_OK;
}
/**
* @brief USB_ReadInterrupts return the global USB interrupt status
* @param USBx Selected device
* @retval HAL status
*/
uint32_t USB_ReadInterrupts(USB_TypeDef *USBx)
{
uint32_t tmpreg;
tmpreg = USBx->ISTR;
return tmpreg;
}
/**
* @brief USB_ActivateRemoteWakeup : active remote wakeup signalling
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR |= (uint16_t)USB_CNTR_RESUME;
return HAL_OK;
}
/**
* @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR &= (uint16_t)(~USB_CNTR_RESUME);
return HAL_OK;
}
/**
* @brief Copy a buffer from user memory area to packet memory area (PMA)
* @param USBx USB peripheral instance register address.
* @param pbUsrBuf pointer to user memory area.
* @param wPMABufAddr address into PMA.
* @param wNBytes no. of bytes to be copied.
* @retval None
*/
void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = ((uint32_t)wNBytes + 1U) >> 1;
uint32_t BaseAddr = (uint32_t)USBx;
uint32_t i;
uint32_t temp1;
uint32_t temp2;
__IO uint16_t *pdwVal;
uint8_t *pBuf = pbUsrBuf;
pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS));
for (i = n; i != 0U; i--)
{
temp1 = *pBuf;
pBuf++;
temp2 = temp1 | ((uint16_t)((uint16_t) *pBuf << 8));
*pdwVal = (uint16_t)temp2;
pdwVal++;
#if PMA_ACCESS > 1U
pdwVal++;
#endif /* PMA_ACCESS */
pBuf++;
}
}
/**
* @brief Copy data from packet memory area (PMA) to user memory buffer
* @param USBx USB peripheral instance register address.
* @param pbUsrBuf pointer to user memory area.
* @param wPMABufAddr address into PMA.
* @param wNBytes no. of bytes to be copied.
* @retval None
*/
void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = (uint32_t)wNBytes >> 1;
uint32_t BaseAddr = (uint32_t)USBx;
uint32_t i;
uint32_t temp;
__IO uint16_t *pdwVal;
uint8_t *pBuf = pbUsrBuf;
pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS));
for (i = n; i != 0U; i--)
{
temp = *(__IO uint16_t *)pdwVal;
pdwVal++;
*pBuf = (uint8_t)((temp >> 0) & 0xFFU);
pBuf++;
*pBuf = (uint8_t)((temp >> 8) & 0xFFU);
pBuf++;
#if PMA_ACCESS > 1U
pdwVal++;
#endif /* PMA_ACCESS */
}
if ((wNBytes % 2U) != 0U)
{
temp = *pdwVal;
*pBuf = (uint8_t)((temp >> 0) & 0xFFU);
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */
/**
* @}
*/

View File

@ -1,175 +0,0 @@
/**
******************************************************************************
* @file usbd_cdc.h
* @author MCD Application Team
* @brief header file for the usbd_cdc.c file.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_CDC_H
#define __USB_CDC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_cdc
* @brief This file is the Header file for usbd_cdc.c
* @{
*/
/** @defgroup usbd_cdc_Exported_Defines
* @{
*/
#define CDC_IN_EP 0x81U /* EP1 for data IN */
#define CDC_OUT_EP 0x01U /* EP1 for data OUT */
#define CDC_CMD_EP 0x82U /* EP2 for CDC commands */
#ifndef CDC_HS_BINTERVAL
#define CDC_HS_BINTERVAL 0x10U
#endif /* CDC_HS_BINTERVAL */
#ifndef CDC_FS_BINTERVAL
#define CDC_FS_BINTERVAL 0x10U
#endif /* CDC_FS_BINTERVAL */
/* CDC Endpoints parameters: you can fine tune these values depending on the needed baudrates and performance. */
#define CDC_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#define CDC_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define CDC_CMD_PACKET_SIZE 8U /* Control Endpoint Packet size */
#define USB_CDC_CONFIG_DESC_SIZ 67U
#define CDC_DATA_HS_IN_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE
#define CDC_DATA_HS_OUT_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE
#define CDC_DATA_FS_IN_PACKET_SIZE CDC_DATA_FS_MAX_PACKET_SIZE
#define CDC_DATA_FS_OUT_PACKET_SIZE CDC_DATA_FS_MAX_PACKET_SIZE
#define CDC_REQ_MAX_DATA_SIZE 0x7U
/*---------------------------------------------------------------------*/
/* CDC definitions */
/*---------------------------------------------------------------------*/
#define CDC_SEND_ENCAPSULATED_COMMAND 0x00U
#define CDC_GET_ENCAPSULATED_RESPONSE 0x01U
#define CDC_SET_COMM_FEATURE 0x02U
#define CDC_GET_COMM_FEATURE 0x03U
#define CDC_CLEAR_COMM_FEATURE 0x04U
#define CDC_SET_LINE_CODING 0x20U
#define CDC_GET_LINE_CODING 0x21U
#define CDC_SET_CONTROL_LINE_STATE 0x22U
#define CDC_SEND_BREAK 0x23U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct
{
uint32_t bitrate;
uint8_t format;
uint8_t paritytype;
uint8_t datatype;
} USBD_CDC_LineCodingTypeDef;
typedef struct _USBD_CDC_Itf
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control)(uint8_t cmd, uint8_t *pbuf, uint16_t length);
int8_t (* Receive)(uint8_t *Buf, uint32_t *Len);
int8_t (* TransmitCplt)(uint8_t *Buf, uint32_t *Len, uint8_t epnum);
} USBD_CDC_ItfTypeDef;
typedef struct
{
uint32_t data[CDC_DATA_HS_MAX_PACKET_SIZE / 4U]; /* Force 32bits alignment */
uint8_t CmdOpCode;
uint8_t CmdLength;
uint8_t *RxBuffer;
uint8_t *TxBuffer;
uint32_t RxLength;
uint32_t TxLength;
__IO uint32_t TxState;
__IO uint32_t RxState;
} USBD_CDC_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CDC;
#define USBD_CDC_CLASS &USBD_CDC
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_CDC_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ItfTypeDef *fops);
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff,
uint32_t length);
uint8_t USBD_CDC_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff);
uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev);
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_CDC_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,968 +0,0 @@
/**
******************************************************************************
* @file usbd_cdc.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB CDC Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as CDC Device (and enumeration for each implemented memory interface)
* - OUT/IN data transfer
* - Command IN transfer (class requests management)
* - Error management
*
* @verbatim
*
* ===================================================================
* CDC Class Driver Description
* ===================================================================
* This driver manages the "Universal Serial Bus Class Definitions for Communications Devices
* Revision 1.2 November 16, 2007" and the sub-protocol specification of "Universal Serial Bus
* Communications Class Subclass Specification for PSTN Devices Revision 1.2 February 9, 2007"
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as CDC device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN)
* - Requests management (as described in section 6.2 in specification)
* - Abstract Control Model compliant
* - Union Functional collection (using 1 IN endpoint for control)
* - Data interface class
*
* These aspects may be enriched or modified for a specific user application.
*
* This driver doesn't implement the following aspects of the specification
* (but it is possible to manage these features with some modifications on this driver):
* - Any class-specific aspect relative to communication classes should be managed by user application.
* - All communication classes other than PSTN are not managed
*
* @endverbatim
*
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CDC
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CDC_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CDC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_CDC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t *USBD_CDC_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc(uint16_t *length);
uint8_t *USBD_CDC_GetDeviceQualifierDescriptor(uint16_t *length);
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Variables
* @{
*/
/* CDC interface class callbacks structure */
USBD_ClassTypeDef USBD_CDC =
{
USBD_CDC_Init,
USBD_CDC_DeInit,
USBD_CDC_Setup,
NULL, /* EP0_TxSent, */
USBD_CDC_EP0_RxReady,
USBD_CDC_DataIn,
USBD_CDC_DataOut,
NULL,
NULL,
NULL,
USBD_CDC_GetHSCfgDesc,
USBD_CDC_GetFSCfgDesc,
USBD_CDC_GetOtherSpeedCfgDesc,
USBD_CDC_GetDeviceQualifierDescriptor,
};
/* USB CDC device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_CfgHSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_CDC_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */
0x00,
0x02, /* bNumInterfaces: 2 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif
USBD_MAX_POWER, /* MaxPower 100 mA */
/*---------------------------------------------------------------------------*/
/* Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoints used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x02, /* bInterfaceSubClass: Abstract Control Model */
0x01, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface: */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header Func Desc */
0x10, /* bcdCDC: spec release number */
0x01,
/* Call Management Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x01, /* bDescriptorSubtype: Call Management Func Desc */
0x00, /* bmCapabilities: D0+D1 */
0x01, /* bDataInterface: 1 */
/* ACM Functional Descriptor */
0x04, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x02, /* bDescriptorSubtype: Abstract Control Management desc */
0x02, /* bmCapabilities */
/* Union Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union func desc */
0x00, /* bMasterInterface: Communication class interface */
0x01, /* bSlaveInterface0: Data Class Interface */
/* Endpoint 2 Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_CMD_PACKET_SIZE),
CDC_HS_BINTERVAL, /* bInterval: */
/*---------------------------------------------------------------------------*/
/* Data class interface descriptor */
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
0x01, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC */
0x00, /* bInterfaceSubClass: */
0x00, /* bInterfaceProtocol: */
0x00, /* iInterface: */
/* Endpoint OUT Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE),
0x00, /* bInterval: ignore for Bulk transfer */
/* Endpoint IN Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE),
0x00 /* bInterval: ignore for Bulk transfer */
};
/* USB CDC device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_CfgFSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_CDC_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */
0x00,
0x02, /* bNumInterfaces: 2 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif
USBD_MAX_POWER, /* MaxPower 100 mA */
/*---------------------------------------------------------------------------*/
/* Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */
/* Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoints used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x02, /* bInterfaceSubClass: Abstract Control Model */
0x01, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface: */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header Func Desc */
0x10, /* bcdCDC: spec release number */
0x01,
/* Call Management Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x01, /* bDescriptorSubtype: Call Management Func Desc */
0x00, /* bmCapabilities: D0+D1 */
0x01, /* bDataInterface: 1 */
/* ACM Functional Descriptor */
0x04, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x02, /* bDescriptorSubtype: Abstract Control Management desc */
0x02, /* bmCapabilities */
/* Union Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union func desc */
0x00, /* bMasterInterface: Communication class interface */
0x01, /* bSlaveInterface0: Data Class Interface */
/* Endpoint 2 Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_CMD_PACKET_SIZE),
CDC_FS_BINTERVAL, /* bInterval: */
/*---------------------------------------------------------------------------*/
/* Data class interface descriptor */
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
0x01, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC */
0x00, /* bInterfaceSubClass: */
0x00, /* bInterfaceProtocol: */
0x00, /* iInterface: */
/* Endpoint OUT Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
0x00, /* bInterval: ignore for Bulk transfer */
/* Endpoint IN Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
0x00 /* bInterval: ignore for Bulk transfer */
};
__ALIGN_BEGIN static uint8_t USBD_CDC_OtherSpeedCfgDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION,
USB_CDC_CONFIG_DESC_SIZ,
0x00,
0x02, /* bNumInterfaces: 2 interfaces */
0x01, /* bConfigurationValue: */
0x04, /* iConfiguration: */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif
USBD_MAX_POWER, /* MaxPower 100 mA */
/*Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */
/* Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoints used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x02, /* bInterfaceSubClass: Abstract Control Model */
0x01, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface: */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header Func Desc */
0x10, /* bcdCDC: spec release number */
0x01,
/*Call Management Functional Descriptor*/
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x01, /* bDescriptorSubtype: Call Management Func Desc */
0x00, /* bmCapabilities: D0+D1 */
0x01, /* bDataInterface: 1 */
/*ACM Functional Descriptor*/
0x04, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x02, /* bDescriptorSubtype: Abstract Control Management desc */
0x02, /* bmCapabilities */
/*Union Functional Descriptor*/
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union func desc */
0x00, /* bMasterInterface: Communication class interface */
0x01, /* bSlaveInterface0: Data Class Interface */
/*Endpoint 2 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_CMD_PACKET_SIZE),
CDC_FS_BINTERVAL, /* bInterval: */
/*---------------------------------------------------------------------------*/
/*Data class interface descriptor*/
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
0x01, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC */
0x00, /* bInterfaceSubClass: */
0x00, /* bInterfaceProtocol: */
0x00, /* iInterface: */
/*Endpoint OUT Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
0x40, /* wMaxPacketSize: */
0x00,
0x00, /* bInterval: ignore for Bulk transfer */
/*Endpoint IN Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
0x40, /* wMaxPacketSize: */
0x00,
0x00 /* bInterval */
};
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Functions
* @{
*/
/**
* @brief USBD_CDC_Init
* Initialize the CDC interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_CDC_HandleTypeDef *hcdc;
hcdc = USBD_malloc(sizeof(USBD_CDC_HandleTypeDef));
if (hcdc == NULL)
{
pdev->pClassData = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassData = (void *)hcdc;
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CDC_IN_EP, USBD_EP_TYPE_BULK,
CDC_DATA_HS_IN_PACKET_SIZE);
pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CDC_OUT_EP, USBD_EP_TYPE_BULK,
CDC_DATA_HS_OUT_PACKET_SIZE);
pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 1U;
/* Set bInterval for CDC CMD Endpoint */
pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = CDC_HS_BINTERVAL;
}
else
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CDC_IN_EP, USBD_EP_TYPE_BULK,
CDC_DATA_FS_IN_PACKET_SIZE);
pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CDC_OUT_EP, USBD_EP_TYPE_BULK,
CDC_DATA_FS_OUT_PACKET_SIZE);
pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 1U;
/* Set bInterval for CMD Endpoint */
pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = CDC_FS_BINTERVAL;
}
/* Open Command IN EP */
(void)USBD_LL_OpenEP(pdev, CDC_CMD_EP, USBD_EP_TYPE_INTR, CDC_CMD_PACKET_SIZE);
pdev->ep_in[CDC_CMD_EP & 0xFU].is_used = 1U;
/* Init physical Interface components */
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Init();
/* Init Xfer states */
hcdc->TxState = 0U;
hcdc->RxState = 0U;
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer,
CDC_DATA_HS_OUT_PACKET_SIZE);
}
else
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer,
CDC_DATA_FS_OUT_PACKET_SIZE);
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_Init
* DeInitialize the CDC layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, CDC_IN_EP);
pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, CDC_OUT_EP);
pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 0U;
/* Close Command IN EP */
(void)USBD_LL_CloseEP(pdev, CDC_CMD_EP);
pdev->ep_in[CDC_CMD_EP & 0xFU].is_used = 0U;
pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = 0U;
/* DeInit physical Interface components */
if (pdev->pClassData != NULL)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->DeInit();
(void)USBD_free(pdev->pClassData);
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_Setup
* Handle the CDC specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CDC_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
uint16_t len;
uint8_t ifalt = 0U;
uint16_t status_info = 0U;
USBD_StatusTypeDef ret = USBD_OK;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
if (req->wLength != 0U)
{
if ((req->bmRequest & 0x80U) != 0U)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Control(req->bRequest,
(uint8_t *)hcdc->data,
req->wLength);
len = MIN(CDC_REQ_MAX_DATA_SIZE, req->wLength);
(void)USBD_CtlSendData(pdev, (uint8_t *)hcdc->data, len);
}
else
{
hcdc->CmdOpCode = req->bRequest;
hcdc->CmdLength = (uint8_t)req->wLength;
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)hcdc->data, req->wLength);
}
}
else
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Control(req->bRequest,
(uint8_t *)req, 0U);
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, &ifalt, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_HandleTypeDef *hcdc;
PCD_HandleTypeDef *hpcd = pdev->pData;
if (pdev->pClassData == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if ((pdev->ep_in[epnum].total_length > 0U) &&
((pdev->ep_in[epnum].total_length % hpcd->IN_ep[epnum].maxpacket) == 0U))
{
/* Update the packet total length */
pdev->ep_in[epnum].total_length = 0U;
/* Send ZLP */
(void)USBD_LL_Transmit(pdev, epnum, NULL, 0U);
}
else
{
hcdc->TxState = 0U;
if (((USBD_CDC_ItfTypeDef *)pdev->pUserData)->TransmitCplt != NULL)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->TransmitCplt(hcdc->TxBuffer, &hcdc->TxLength, epnum);
}
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if (pdev->pClassData == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Get the received data length */
hcdc->RxLength = USBD_LL_GetRxDataSize(pdev, epnum);
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application Xfer */
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Receive(hcdc->RxBuffer, &hcdc->RxLength);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_EP0_RxReady
* Handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_CDC_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((pdev->pUserData != NULL) && (hcdc->CmdOpCode != 0xFFU))
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Control(hcdc->CmdOpCode,
(uint8_t *)hcdc->data,
(uint16_t)hcdc->CmdLength);
hcdc->CmdOpCode = 0xFFU;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_GetFSCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetFSCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_CfgFSDesc);
return USBD_CDC_CfgFSDesc;
}
/**
* @brief USBD_CDC_GetHSCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetHSCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_CfgHSDesc);
return USBD_CDC_CfgHSDesc;
}
/**
* @brief USBD_CDC_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_OtherSpeedCfgDesc);
return USBD_CDC_OtherSpeedCfgDesc;
}
/**
* @brief USBD_CDC_GetDeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CDC_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_DeviceQualifierDesc);
return USBD_CDC_DeviceQualifierDesc;
}
/**
* @brief USBD_CDC_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_CDC_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData = fops;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_SetTxBuffer
* @param pdev: device instance
* @param pbuff: Tx Buffer
* @retval status
*/
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev,
uint8_t *pbuff, uint32_t length)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->TxBuffer = pbuff;
hcdc->TxLength = length;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_SetRxBuffer
* @param pdev: device instance
* @param pbuff: Rx Buffer
* @retval status
*/
uint8_t USBD_CDC_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->RxBuffer = pbuff;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_TransmitPacket
* Transmit packet on IN endpoint
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
USBD_StatusTypeDef ret = USBD_BUSY;
if (pdev->pClassData == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (hcdc->TxState == 0U)
{
/* Tx Transfer in progress */
hcdc->TxState = 1U;
/* Update the packet total length */
pdev->ep_in[CDC_IN_EP & 0xFU].total_length = hcdc->TxLength;
/* Transmit next packet */
(void)USBD_LL_Transmit(pdev, CDC_IN_EP, hcdc->TxBuffer, hcdc->TxLength);
ret = USBD_OK;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;
if (pdev->pClassData == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer,
CDC_DATA_HS_OUT_PACKET_SIZE);
}
else
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer,
CDC_DATA_FS_OUT_PACKET_SIZE);
}
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,158 +0,0 @@
/**
******************************************************************************
* @file usbd_core.h
* @author MCD Application Team
* @brief Header file for usbd_core.c file
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CORE_H
#define __USBD_CORE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_conf.h"
#include "usbd_def.h"
#include "usbd_ioreq.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CORE
* @brief This file is the Header file for usbd_core.c file
* @{
*/
/** @defgroup USBD_CORE_Exported_Defines
* @{
*/
#ifndef USBD_DEBUG_LEVEL
#define USBD_DEBUG_LEVEL 0U
#endif /* USBD_DEBUG_LEVEL */
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
#define USBD_SOF USBD_LL_SOF
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id);
USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_Start(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_Stop(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass);
USBD_StatusTypeDef USBD_RunTestMode(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup);
USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev, uint8_t epnum, uint8_t *pdata);
USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev, uint8_t epnum, uint8_t *pdata);
USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed);
USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev);
/* USBD Low Level Driver */
USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t ep_type, uint16_t ep_mps);
USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev, uint8_t dev_addr);
USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t *pbuf, uint32_t size);
USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t *pbuf, uint32_t size);
uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
void USBD_LL_Delay(uint32_t Delay);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CORE_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,103 +0,0 @@
/**
******************************************************************************
* @file usbd_req.h
* @author MCD Application Team
* @brief Header file for the usbd_req.c file
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_REQUEST_H
#define __USB_REQUEST_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_REQ
* @brief header file for the usbd_req.c file
* @{
*/
/** @defgroup USBD_REQ_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_StdDevReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
USBD_StatusTypeDef USBD_StdItfReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
USBD_StatusTypeDef USBD_StdEPReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
void USBD_CtlError(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata);
void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_REQUEST_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,420 +0,0 @@
/**
******************************************************************************
* @file usbd_def.h
* @author MCD Application Team
* @brief General defines for the usb device library
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_DEF_H
#define __USBD_DEF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_conf.h"
/** @addtogroup STM32_USBD_DEVICE_LIBRARY
* @{
*/
/** @defgroup USB_DEF
* @brief general defines for the usb device library file
* @{
*/
/** @defgroup USB_DEF_Exported_Defines
* @{
*/
#ifndef NULL
#define NULL 0U
#endif /* NULL */
#ifndef USBD_MAX_NUM_INTERFACES
#define USBD_MAX_NUM_INTERFACES 1U
#endif /* USBD_MAX_NUM_CONFIGURATION */
#ifndef USBD_MAX_NUM_CONFIGURATION
#define USBD_MAX_NUM_CONFIGURATION 1U
#endif /* USBD_MAX_NUM_CONFIGURATION */
#ifndef USBD_LPM_ENABLED
#define USBD_LPM_ENABLED 0U
#endif /* USBD_LPM_ENABLED */
#ifndef USBD_SELF_POWERED
#define USBD_SELF_POWERED 1U
#endif /*USBD_SELF_POWERED */
#ifndef USBD_MAX_POWER
#define USBD_MAX_POWER 0x32U /* 100 mA */
#endif /* USBD_MAX_POWER */
#ifndef USBD_SUPPORT_USER_STRING_DESC
#define USBD_SUPPORT_USER_STRING_DESC 0U
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#ifndef USBD_CLASS_USER_STRING_DESC
#define USBD_CLASS_USER_STRING_DESC 0U
#endif /* USBD_CLASS_USER_STRING_DESC */
#define USB_LEN_DEV_QUALIFIER_DESC 0x0AU
#define USB_LEN_DEV_DESC 0x12U
#define USB_LEN_CFG_DESC 0x09U
#define USB_LEN_IF_DESC 0x09U
#define USB_LEN_EP_DESC 0x07U
#define USB_LEN_OTG_DESC 0x03U
#define USB_LEN_LANGID_STR_DESC 0x04U
#define USB_LEN_OTHER_SPEED_DESC_SIZ 0x09U
#define USBD_IDX_LANGID_STR 0x00U
#define USBD_IDX_MFC_STR 0x01U
#define USBD_IDX_PRODUCT_STR 0x02U
#define USBD_IDX_SERIAL_STR 0x03U
#define USBD_IDX_CONFIG_STR 0x04U
#define USBD_IDX_INTERFACE_STR 0x05U
#define USB_REQ_TYPE_STANDARD 0x00U
#define USB_REQ_TYPE_CLASS 0x20U
#define USB_REQ_TYPE_VENDOR 0x40U
#define USB_REQ_TYPE_MASK 0x60U
#define USB_REQ_RECIPIENT_DEVICE 0x00U
#define USB_REQ_RECIPIENT_INTERFACE 0x01U
#define USB_REQ_RECIPIENT_ENDPOINT 0x02U
#define USB_REQ_RECIPIENT_MASK 0x03U
#define USB_REQ_GET_STATUS 0x00U
#define USB_REQ_CLEAR_FEATURE 0x01U
#define USB_REQ_SET_FEATURE 0x03U
#define USB_REQ_SET_ADDRESS 0x05U
#define USB_REQ_GET_DESCRIPTOR 0x06U
#define USB_REQ_SET_DESCRIPTOR 0x07U
#define USB_REQ_GET_CONFIGURATION 0x08U
#define USB_REQ_SET_CONFIGURATION 0x09U
#define USB_REQ_GET_INTERFACE 0x0AU
#define USB_REQ_SET_INTERFACE 0x0BU
#define USB_REQ_SYNCH_FRAME 0x0CU
#define USB_DESC_TYPE_DEVICE 0x01U
#define USB_DESC_TYPE_CONFIGURATION 0x02U
#define USB_DESC_TYPE_STRING 0x03U
#define USB_DESC_TYPE_INTERFACE 0x04U
#define USB_DESC_TYPE_ENDPOINT 0x05U
#define USB_DESC_TYPE_DEVICE_QUALIFIER 0x06U
#define USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION 0x07U
#define USB_DESC_TYPE_IAD 0x0BU
#define USB_DESC_TYPE_BOS 0x0FU
#define USB_CONFIG_REMOTE_WAKEUP 0x02U
#define USB_CONFIG_SELF_POWERED 0x01U
#define USB_FEATURE_EP_HALT 0x00U
#define USB_FEATURE_REMOTE_WAKEUP 0x01U
#define USB_FEATURE_TEST_MODE 0x02U
#define USB_DEVICE_CAPABITY_TYPE 0x10U
#define USB_CONF_DESC_SIZE 0x09U
#define USB_IF_DESC_SIZE 0x09U
#define USB_EP_DESC_SIZE 0x07U
#define USB_IAD_DESC_SIZE 0x08U
#define USB_HS_MAX_PACKET_SIZE 512U
#define USB_FS_MAX_PACKET_SIZE 64U
#define USB_MAX_EP0_SIZE 64U
/* Device Status */
#define USBD_STATE_DEFAULT 0x01U
#define USBD_STATE_ADDRESSED 0x02U
#define USBD_STATE_CONFIGURED 0x03U
#define USBD_STATE_SUSPENDED 0x04U
/* EP0 State */
#define USBD_EP0_IDLE 0x00U
#define USBD_EP0_SETUP 0x01U
#define USBD_EP0_DATA_IN 0x02U
#define USBD_EP0_DATA_OUT 0x03U
#define USBD_EP0_STATUS_IN 0x04U
#define USBD_EP0_STATUS_OUT 0x05U
#define USBD_EP0_STALL 0x06U
#define USBD_EP_TYPE_CTRL 0x00U
#define USBD_EP_TYPE_ISOC 0x01U
#define USBD_EP_TYPE_BULK 0x02U
#define USBD_EP_TYPE_INTR 0x03U
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_TypesDefinitions
* @{
*/
typedef struct usb_setup_req
{
uint8_t bmRequest;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} USBD_SetupReqTypedef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} USBD_ConfigDescTypedef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumDeviceCaps;
} USBD_BosDescTypedef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} USBD_EpDescTypedef;
struct _USBD_HandleTypeDef;
typedef struct _Device_cb
{
uint8_t (*Init)(struct _USBD_HandleTypeDef *pdev, uint8_t cfgidx);
uint8_t (*DeInit)(struct _USBD_HandleTypeDef *pdev, uint8_t cfgidx);
/* Control Endpoints*/
uint8_t (*Setup)(struct _USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
uint8_t (*EP0_TxSent)(struct _USBD_HandleTypeDef *pdev);
uint8_t (*EP0_RxReady)(struct _USBD_HandleTypeDef *pdev);
/* Class Specific Endpoints*/
uint8_t (*DataIn)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*DataOut)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*SOF)(struct _USBD_HandleTypeDef *pdev);
uint8_t (*IsoINIncomplete)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*IsoOUTIncomplete)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t *(*GetHSConfigDescriptor)(uint16_t *length);
uint8_t *(*GetFSConfigDescriptor)(uint16_t *length);
uint8_t *(*GetOtherSpeedConfigDescriptor)(uint16_t *length);
uint8_t *(*GetDeviceQualifierDescriptor)(uint16_t *length);
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
uint8_t *(*GetUsrStrDescriptor)(struct _USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length);
#endif
} USBD_ClassTypeDef;
/* Following USB Device Speed */
typedef enum
{
USBD_SPEED_HIGH = 0U,
USBD_SPEED_FULL = 1U,
USBD_SPEED_LOW = 2U,
} USBD_SpeedTypeDef;
/* Following USB Device status */
typedef enum
{
USBD_OK = 0U,
USBD_BUSY,
USBD_EMEM,
USBD_FAIL,
} USBD_StatusTypeDef;
/* USB Device descriptors structure */
typedef struct
{
uint8_t *(*GetDeviceDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetLangIDStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetManufacturerStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetProductStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetSerialStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetConfigurationStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetInterfaceStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
#if (USBD_CLASS_USER_STRING_DESC == 1)
uint8_t *(*GetUserStrDescriptor)(USBD_SpeedTypeDef speed, uint8_t idx, uint16_t *length);
#endif
#if ((USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1))
uint8_t *(*GetBOSDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
#endif
} USBD_DescriptorsTypeDef;
/* USB Device handle structure */
typedef struct
{
uint32_t status;
uint32_t total_length;
uint32_t rem_length;
uint32_t maxpacket;
uint16_t is_used;
uint16_t bInterval;
} USBD_EndpointTypeDef;
/* USB Device handle structure */
typedef struct _USBD_HandleTypeDef
{
uint8_t id;
uint32_t dev_config;
uint32_t dev_default_config;
uint32_t dev_config_status;
USBD_SpeedTypeDef dev_speed;
USBD_EndpointTypeDef ep_in[16];
USBD_EndpointTypeDef ep_out[16];
__IO uint32_t ep0_state;
uint32_t ep0_data_len;
__IO uint8_t dev_state;
__IO uint8_t dev_old_state;
uint8_t dev_address;
uint8_t dev_connection_status;
uint8_t dev_test_mode;
uint32_t dev_remote_wakeup;
uint8_t ConfIdx;
USBD_SetupReqTypedef request;
USBD_DescriptorsTypeDef *pDesc;
USBD_ClassTypeDef *pClass;
void *pClassData;
void *pUserData;
void *pData;
void *pBosDesc;
void *pConfDesc;
} USBD_HandleTypeDef;
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_Macros
* @{
*/
__STATIC_INLINE uint16_t SWAPBYTE(uint8_t *addr)
{
uint16_t _SwapVal, _Byte1, _Byte2;
uint8_t *_pbuff = addr;
_Byte1 = *(uint8_t *)_pbuff;
_pbuff++;
_Byte2 = *(uint8_t *)_pbuff;
_SwapVal = (_Byte2 << 8) | _Byte1;
return _SwapVal;
}
#ifndef LOBYTE
#define LOBYTE(x) ((uint8_t)((x) & 0x00FFU))
#endif
#ifndef HIBYTE
#define HIBYTE(x) ((uint8_t)(((x) & 0xFF00U) >> 8U))
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#if defined ( __GNUC__ )
#ifndef __weak
#define __weak __attribute__((weak))
#endif /* __weak */
#ifndef __packed
#define __packed __attribute__((__packed__))
#endif /* __packed */
#endif /* __GNUC__ */
/* In HS mode and when the DMA is used, all variables and data structures dealing
with the DMA during the transaction process should be 4-bytes aligned */
#if defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */
#ifndef __ALIGN_END
#define __ALIGN_END __attribute__ ((aligned (4U)))
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#define __ALIGN_BEGIN
#endif /* __ALIGN_BEGIN */
#else
#ifndef __ALIGN_END
#define __ALIGN_END
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#if defined (__CC_ARM) /* ARM Compiler */
#define __ALIGN_BEGIN __align(4U)
#elif defined (__ICCARM__) /* IAR Compiler */
#define __ALIGN_BEGIN
#endif /* __CC_ARM */
#endif /* __ALIGN_BEGIN */
#endif /* __GNUC__ */
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_DEF_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,114 +0,0 @@
/**
******************************************************************************
* @file usbd_ioreq.h
* @author MCD Application Team
* @brief Header file for the usbd_ioreq.c file
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_IOREQ_H
#define __USBD_IOREQ_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
#include "usbd_core.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_IOREQ
* @brief header file for the usbd_ioreq.c file
* @{
*/
/** @defgroup USBD_IOREQ_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_CtlSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlContinueSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlPrepareRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlContinueRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlSendStatus(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_CtlReceiveStatus(USBD_HandleTypeDef *pdev);
uint32_t USBD_GetRxCount(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_IOREQ_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,694 +0,0 @@
/**
******************************************************************************
* @file usbd_core.c
* @author MCD Application Team
* @brief This file provides all the USBD core functions.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_core.h"
/** @addtogroup STM32_USBD_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CORE
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CORE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Functions
* @{
*/
/**
* @brief USBD_Init
* Initializes the device stack and load the class driver
* @param pdev: device instance
* @param pdesc: Descriptor structure address
* @param id: Low level core index
* @retval None
*/
USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev,
USBD_DescriptorsTypeDef *pdesc, uint8_t id)
{
USBD_StatusTypeDef ret;
/* Check whether the USB Host handle is valid */
if (pdev == NULL)
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Invalid Device handle");
#endif
return USBD_FAIL;
}
/* Unlink previous class resources */
pdev->pClass = NULL;
pdev->pUserData = NULL;
pdev->pConfDesc = NULL;
/* Assign USBD Descriptors */
if (pdesc != NULL)
{
pdev->pDesc = pdesc;
}
/* Set Device initial State */
pdev->dev_state = USBD_STATE_DEFAULT;
pdev->id = id;
/* Initialize low level driver */
ret = USBD_LL_Init(pdev);
return ret;
}
/**
* @brief USBD_DeInit
* Re-Initialize the device library
* @param pdev: device instance
* @retval status: status
*/
USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev)
{
USBD_StatusTypeDef ret;
/* Disconnect the USB Device */
(void)USBD_LL_Stop(pdev);
/* Set Default State */
pdev->dev_state = USBD_STATE_DEFAULT;
/* Free Class Resources */
if (pdev->pClass != NULL)
{
pdev->pClass->DeInit(pdev, (uint8_t)pdev->dev_config);
pdev->pClass = NULL;
pdev->pUserData = NULL;
}
/* Free Device descriptors resources */
pdev->pDesc = NULL;
pdev->pConfDesc = NULL;
/* DeInitialize low level driver */
ret = USBD_LL_DeInit(pdev);
return ret;
}
/**
* @brief USBD_RegisterClass
* Link class driver to Device Core.
* @param pDevice : Device Handle
* @param pclass: Class handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass)
{
uint16_t len = 0U;
if (pclass == NULL)
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Invalid Class handle");
#endif
return USBD_FAIL;
}
/* link the class to the USB Device handle */
pdev->pClass = pclass;
/* Get Device Configuration Descriptor */
#ifdef USE_USB_HS
if (pdev->pClass->GetHSConfigDescriptor != NULL)
{
pdev->pConfDesc = (void *)pdev->pClass->GetHSConfigDescriptor(&len);
}
#else /* Default USE_USB_FS */
if (pdev->pClass->GetFSConfigDescriptor != NULL)
{
pdev->pConfDesc = (void *)pdev->pClass->GetFSConfigDescriptor(&len);
}
#endif /* USE_USB_FS */
return USBD_OK;
}
/**
* @brief USBD_Start
* Start the USB Device Core.
* @param pdev: Device Handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_Start(USBD_HandleTypeDef *pdev)
{
/* Start the low level driver */
return USBD_LL_Start(pdev);
}
/**
* @brief USBD_Stop
* Stop the USB Device Core.
* @param pdev: Device Handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_Stop(USBD_HandleTypeDef *pdev)
{
/* Disconnect USB Device */
(void)USBD_LL_Stop(pdev);
/* Free Class Resources */
if (pdev->pClass != NULL)
{
(void)pdev->pClass->DeInit(pdev, (uint8_t)pdev->dev_config);
}
return USBD_OK;
}
/**
* @brief USBD_RunTestMode
* Launch test mode process
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_RunTestMode(USBD_HandleTypeDef *pdev)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief USBD_SetClassConfig
* Configure device and start the interface
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status
*/
USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
USBD_StatusTypeDef ret = USBD_FAIL;
if (pdev->pClass != NULL)
{
/* Set configuration and Start the Class */
ret = (USBD_StatusTypeDef)pdev->pClass->Init(pdev, cfgidx);
}
return ret;
}
/**
* @brief USBD_ClrClassConfig
* Clear current configuration
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status: USBD_StatusTypeDef
*/
USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
/* Clear configuration and De-initialize the Class process */
if (pdev->pClass != NULL)
{
pdev->pClass->DeInit(pdev, cfgidx);
}
return USBD_OK;
}
/**
* @brief USBD_LL_SetupStage
* Handle the setup stage
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup)
{
USBD_StatusTypeDef ret;
USBD_ParseSetupRequest(&pdev->request, psetup);
pdev->ep0_state = USBD_EP0_SETUP;
pdev->ep0_data_len = pdev->request.wLength;
switch (pdev->request.bmRequest & 0x1FU)
{
case USB_REQ_RECIPIENT_DEVICE:
ret = USBD_StdDevReq(pdev, &pdev->request);
break;
case USB_REQ_RECIPIENT_INTERFACE:
ret = USBD_StdItfReq(pdev, &pdev->request);
break;
case USB_REQ_RECIPIENT_ENDPOINT:
ret = USBD_StdEPReq(pdev, &pdev->request);
break;
default:
ret = USBD_LL_StallEP(pdev, (pdev->request.bmRequest & 0x80U));
break;
}
return ret;
}
/**
* @brief USBD_LL_DataOutStage
* Handle data OUT stage
* @param pdev: device instance
* @param epnum: endpoint index
* @param pdata: data pointer
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev,
uint8_t epnum, uint8_t *pdata)
{
USBD_EndpointTypeDef *pep;
USBD_StatusTypeDef ret;
if (epnum == 0U)
{
pep = &pdev->ep_out[0];
if (pdev->ep0_state == USBD_EP0_DATA_OUT)
{
if (pep->rem_length > pep->maxpacket)
{
pep->rem_length -= pep->maxpacket;
(void)USBD_CtlContinueRx(pdev, pdata, MIN(pep->rem_length, pep->maxpacket));
}
else
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->EP0_RxReady != NULL)
{
pdev->pClass->EP0_RxReady(pdev);
}
}
(void)USBD_CtlSendStatus(pdev);
}
}
else
{
#if 0
if (pdev->ep0_state == USBD_EP0_STATUS_OUT)
{
/*
* STATUS PHASE completed, update ep0_state to idle
*/
pdev->ep0_state = USBD_EP0_IDLE;
(void)USBD_LL_StallEP(pdev, 0U);
}
#endif
}
}
else
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->DataOut != NULL)
{
ret = (USBD_StatusTypeDef)pdev->pClass->DataOut(pdev, epnum);
if (ret != USBD_OK)
{
return ret;
}
}
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_DataInStage
* Handle data in stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev,
uint8_t epnum, uint8_t *pdata)
{
USBD_EndpointTypeDef *pep;
USBD_StatusTypeDef ret;
if (epnum == 0U)
{
pep = &pdev->ep_in[0];
if (pdev->ep0_state == USBD_EP0_DATA_IN)
{
if (pep->rem_length > pep->maxpacket)
{
pep->rem_length -= pep->maxpacket;
(void)USBD_CtlContinueSendData(pdev, pdata, pep->rem_length);
/* Prepare endpoint for premature end of transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
}
else
{
/* last packet is MPS multiple, so send ZLP packet */
if ((pep->maxpacket == pep->rem_length) &&
(pep->total_length >= pep->maxpacket) &&
(pep->total_length < pdev->ep0_data_len))
{
(void)USBD_CtlContinueSendData(pdev, NULL, 0U);
pdev->ep0_data_len = 0U;
/* Prepare endpoint for premature end of transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
}
else
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->EP0_TxSent != NULL)
{
pdev->pClass->EP0_TxSent(pdev);
}
}
(void)USBD_LL_StallEP(pdev, 0x80U);
(void)USBD_CtlReceiveStatus(pdev);
}
}
}
else
{
#if 0
if ((pdev->ep0_state == USBD_EP0_STATUS_IN) ||
(pdev->ep0_state == USBD_EP0_IDLE))
{
(void)USBD_LL_StallEP(pdev, 0x80U);
}
#endif
}
if (pdev->dev_test_mode == 1U)
{
(void)USBD_RunTestMode(pdev);
pdev->dev_test_mode = 0U;
}
}
else
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->DataIn != NULL)
{
ret = (USBD_StatusTypeDef)pdev->pClass->DataIn(pdev, epnum);
if (ret != USBD_OK)
{
return ret;
}
}
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_Reset
* Handle Reset event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev)
{
/* Upon Reset call user call back */
pdev->dev_state = USBD_STATE_DEFAULT;
pdev->ep0_state = USBD_EP0_IDLE;
pdev->dev_config = 0U;
pdev->dev_remote_wakeup = 0U;
if (pdev->pClass == NULL)
{
return USBD_FAIL;
}
if (pdev->pClassData != NULL)
{
if (pdev->pClass->DeInit != NULL)
{
(void)pdev->pClass->DeInit(pdev, (uint8_t)pdev->dev_config);
}
}
/* Open EP0 OUT */
(void)USBD_LL_OpenEP(pdev, 0x00U, USBD_EP_TYPE_CTRL, USB_MAX_EP0_SIZE);
pdev->ep_out[0x00U & 0xFU].is_used = 1U;
pdev->ep_out[0].maxpacket = USB_MAX_EP0_SIZE;
/* Open EP0 IN */
(void)USBD_LL_OpenEP(pdev, 0x80U, USBD_EP_TYPE_CTRL, USB_MAX_EP0_SIZE);
pdev->ep_in[0x80U & 0xFU].is_used = 1U;
pdev->ep_in[0].maxpacket = USB_MAX_EP0_SIZE;
return USBD_OK;
}
/**
* @brief USBD_LL_SetSpeed
* Handle Reset event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev,
USBD_SpeedTypeDef speed)
{
pdev->dev_speed = speed;
return USBD_OK;
}
/**
* @brief USBD_LL_Suspend
* Handle Suspend event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev)
{
pdev->dev_old_state = pdev->dev_state;
pdev->dev_state = USBD_STATE_SUSPENDED;
return USBD_OK;
}
/**
* @brief USBD_LL_Resume
* Handle Resume event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev)
{
if (pdev->dev_state == USBD_STATE_SUSPENDED)
{
pdev->dev_state = pdev->dev_old_state;
}
return USBD_OK;
}
/**
* @brief USBD_LL_SOF
* Handle SOF event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev)
{
if (pdev->pClass == NULL)
{
return USBD_FAIL;
}
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->SOF != NULL)
{
(void)pdev->pClass->SOF(pdev);
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_IsoINIncomplete
* Handle iso in incomplete event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev,
uint8_t epnum)
{
if (pdev->pClass == NULL)
{
return USBD_FAIL;
}
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->IsoINIncomplete != NULL)
{
(void)pdev->pClass->IsoINIncomplete(pdev, epnum);
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_IsoOUTIncomplete
* Handle iso out incomplete event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev,
uint8_t epnum)
{
if (pdev->pClass == NULL)
{
return USBD_FAIL;
}
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass->IsoOUTIncomplete != NULL)
{
(void)pdev->pClass->IsoOUTIncomplete(pdev, epnum);
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_DevConnected
* Handle device connection event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief USBD_LL_DevDisconnected
* Handle device disconnection event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev)
{
/* Free Class Resources */
pdev->dev_state = USBD_STATE_DEFAULT;
if (pdev->pClass != NULL)
{
(void)pdev->pClass->DeInit(pdev, (uint8_t)pdev->dev_config);
}
return USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,948 +0,0 @@
/**
******************************************************************************
* @file usbd_req.c
* @author MCD Application Team
* @brief This file provides the standard USB requests following chapter 9.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ctlreq.h"
#include "usbd_ioreq.h"
/** @addtogroup STM32_USBD_STATE_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_REQ
* @brief USB standard requests module
* @{
*/
/** @defgroup USBD_REQ_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_FunctionPrototypes
* @{
*/
static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_SetAddress(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static USBD_StatusTypeDef USBD_SetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_GetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_GetStatus(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_SetFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_ClrFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_GetLen(uint8_t *buf);
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Functions
* @{
*/
/**
* @brief USBD_StdDevReq
* Handle standard usb device requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdDevReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
ret = (USBD_StatusTypeDef)pdev->pClass->Setup(pdev, req);
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_DESCRIPTOR:
USBD_GetDescriptor(pdev, req);
break;
case USB_REQ_SET_ADDRESS:
USBD_SetAddress(pdev, req);
break;
case USB_REQ_SET_CONFIGURATION:
ret = USBD_SetConfig(pdev, req);
break;
case USB_REQ_GET_CONFIGURATION:
USBD_GetConfig(pdev, req);
break;
case USB_REQ_GET_STATUS:
USBD_GetStatus(pdev, req);
break;
case USB_REQ_SET_FEATURE:
USBD_SetFeature(pdev, req);
break;
case USB_REQ_CLEAR_FEATURE:
USBD_ClrFeature(pdev, req);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_StdItfReq
* Handle standard usb interface requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdItfReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
case USB_REQ_TYPE_STANDARD:
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (LOBYTE(req->wIndex) <= USBD_MAX_NUM_INTERFACES)
{
ret = (USBD_StatusTypeDef)pdev->pClass->Setup(pdev, req);
if ((req->wLength == 0U) && (ret == USBD_OK))
{
(void)USBD_CtlSendStatus(pdev);
}
}
else
{
USBD_CtlError(pdev, req);
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_StdEPReq
* Handle standard usb endpoint requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdEPReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_EndpointTypeDef *pep;
uint8_t ep_addr;
USBD_StatusTypeDef ret = USBD_OK;
ep_addr = LOBYTE(req->wIndex);
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
ret = (USBD_StatusTypeDef)pdev->pClass->Setup(pdev, req);
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_SET_FEATURE:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
(void)USBD_LL_StallEP(pdev, 0x80U);
}
else
{
USBD_CtlError(pdev, req);
}
break;
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_EP_HALT)
{
if ((ep_addr != 0x00U) && (ep_addr != 0x80U) && (req->wLength == 0x00U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
}
}
(void)USBD_CtlSendStatus(pdev);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
case USB_REQ_CLEAR_FEATURE:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
(void)USBD_LL_StallEP(pdev, 0x80U);
}
else
{
USBD_CtlError(pdev, req);
}
break;
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_EP_HALT)
{
if ((ep_addr & 0x7FU) != 0x00U)
{
(void)USBD_LL_ClearStallEP(pdev, ep_addr);
}
(void)USBD_CtlSendStatus(pdev);
ret = (USBD_StatusTypeDef)pdev->pClass->Setup(pdev, req);
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
case USB_REQ_GET_STATUS:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
USBD_CtlError(pdev, req);
break;
}
pep = ((ep_addr & 0x80U) == 0x80U) ? &pdev->ep_in[ep_addr & 0x7FU] : \
&pdev->ep_out[ep_addr & 0x7FU];
pep->status = 0x0000U;
(void)USBD_CtlSendData(pdev, (uint8_t *)&pep->status, 2U);
break;
case USBD_STATE_CONFIGURED:
if ((ep_addr & 0x80U) == 0x80U)
{
if (pdev->ep_in[ep_addr & 0xFU].is_used == 0U)
{
USBD_CtlError(pdev, req);
break;
}
}
else
{
if (pdev->ep_out[ep_addr & 0xFU].is_used == 0U)
{
USBD_CtlError(pdev, req);
break;
}
}
pep = ((ep_addr & 0x80U) == 0x80U) ? &pdev->ep_in[ep_addr & 0x7FU] : \
&pdev->ep_out[ep_addr & 0x7FU];
if ((ep_addr == 0x00U) || (ep_addr == 0x80U))
{
pep->status = 0x0000U;
}
else if (USBD_LL_IsStallEP(pdev, ep_addr) != 0U)
{
pep->status = 0x0001U;
}
else
{
pep->status = 0x0000U;
}
(void)USBD_CtlSendData(pdev, (uint8_t *)&pep->status, 2U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_GetDescriptor
* Handle Get Descriptor requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
uint16_t len = 0U;
uint8_t *pbuf = NULL;
uint8_t err = 0U;
switch (req->wValue >> 8)
{
#if ((USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1U))
case USB_DESC_TYPE_BOS:
if (pdev->pDesc->GetBOSDescriptor != NULL)
{
pbuf = pdev->pDesc->GetBOSDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
#endif
case USB_DESC_TYPE_DEVICE:
pbuf = pdev->pDesc->GetDeviceDescriptor(pdev->dev_speed, &len);
break;
case USB_DESC_TYPE_CONFIGURATION:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pbuf = pdev->pClass->GetHSConfigDescriptor(&len);
pbuf[1] = USB_DESC_TYPE_CONFIGURATION;
}
else
{
pbuf = pdev->pClass->GetFSConfigDescriptor(&len);
pbuf[1] = USB_DESC_TYPE_CONFIGURATION;
}
break;
case USB_DESC_TYPE_STRING:
switch ((uint8_t)(req->wValue))
{
case USBD_IDX_LANGID_STR:
if (pdev->pDesc->GetLangIDStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetLangIDStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_MFC_STR:
if (pdev->pDesc->GetManufacturerStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetManufacturerStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_PRODUCT_STR:
if (pdev->pDesc->GetProductStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetProductStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_SERIAL_STR:
if (pdev->pDesc->GetSerialStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetSerialStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_CONFIG_STR:
if (pdev->pDesc->GetConfigurationStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetConfigurationStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_INTERFACE_STR:
if (pdev->pDesc->GetInterfaceStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetInterfaceStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
default:
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
if (pdev->pClass->GetUsrStrDescriptor != NULL)
{
pbuf = pdev->pClass->GetUsrStrDescriptor(pdev, (req->wValue), &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
#endif
#if (USBD_CLASS_USER_STRING_DESC == 1U)
if (pdev->pDesc->GetUserStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetUserStrDescriptor(pdev->dev_speed, (req->wValue), &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
#endif
#if ((USBD_CLASS_USER_STRING_DESC == 0U) && (USBD_SUPPORT_USER_STRING_DESC == 0U))
USBD_CtlError(pdev, req);
err++;
#endif
break;
}
break;
case USB_DESC_TYPE_DEVICE_QUALIFIER:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pbuf = pdev->pClass->GetDeviceQualifierDescriptor(&len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pbuf = pdev->pClass->GetOtherSpeedConfigDescriptor(&len);
pbuf[1] = USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION;
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
default:
USBD_CtlError(pdev, req);
err++;
break;
}
if (err != 0U)
{
return;
}
if (req->wLength != 0U)
{
if (len != 0U)
{
len = MIN(len, req->wLength);
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
USBD_CtlError(pdev, req);
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
}
/**
* @brief USBD_SetAddress
* Set device address
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_SetAddress(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
uint8_t dev_addr;
if ((req->wIndex == 0U) && (req->wLength == 0U) && (req->wValue < 128U))
{
dev_addr = (uint8_t)(req->wValue) & 0x7FU;
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
}
else
{
pdev->dev_address = dev_addr;
(void)USBD_LL_SetUSBAddress(pdev, dev_addr);
(void)USBD_CtlSendStatus(pdev);
if (dev_addr != 0U)
{
pdev->dev_state = USBD_STATE_ADDRESSED;
}
else
{
pdev->dev_state = USBD_STATE_DEFAULT;
}
}
}
else
{
USBD_CtlError(pdev, req);
}
}
/**
* @brief USBD_SetConfig
* Handle Set device configuration request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static USBD_StatusTypeDef USBD_SetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
static uint8_t cfgidx;
cfgidx = (uint8_t)(req->wValue);
if (cfgidx > USBD_MAX_NUM_CONFIGURATION)
{
USBD_CtlError(pdev, req);
return USBD_FAIL;
}
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if (cfgidx != 0U)
{
pdev->dev_config = cfgidx;
ret = USBD_SetClassConfig(pdev, cfgidx);
if (ret != USBD_OK)
{
USBD_CtlError(pdev, req);
}
else
{
(void)USBD_CtlSendStatus(pdev);
pdev->dev_state = USBD_STATE_CONFIGURED;
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
break;
case USBD_STATE_CONFIGURED:
if (cfgidx == 0U)
{
pdev->dev_state = USBD_STATE_ADDRESSED;
pdev->dev_config = cfgidx;
(void)USBD_ClrClassConfig(pdev, cfgidx);
(void)USBD_CtlSendStatus(pdev);
}
else if (cfgidx != pdev->dev_config)
{
/* Clear old configuration */
(void)USBD_ClrClassConfig(pdev, (uint8_t)pdev->dev_config);
/* set new configuration */
pdev->dev_config = cfgidx;
ret = USBD_SetClassConfig(pdev, cfgidx);
if (ret != USBD_OK)
{
USBD_CtlError(pdev, req);
(void)USBD_ClrClassConfig(pdev, (uint8_t)pdev->dev_config);
pdev->dev_state = USBD_STATE_ADDRESSED;
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
break;
default:
USBD_CtlError(pdev, req);
(void)USBD_ClrClassConfig(pdev, cfgidx);
ret = USBD_FAIL;
break;
}
return ret;
}
/**
* @brief USBD_GetConfig
* Handle Get device configuration request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
if (req->wLength != 1U)
{
USBD_CtlError(pdev, req);
}
else
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
pdev->dev_default_config = 0U;
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_default_config, 1U);
break;
case USBD_STATE_CONFIGURED:
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_config, 1U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
}
/**
* @brief USBD_GetStatus
* Handle Get Status request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetStatus(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (req->wLength != 0x2U)
{
USBD_CtlError(pdev, req);
break;
}
#if (USBD_SELF_POWERED == 1U)
pdev->dev_config_status = USB_CONFIG_SELF_POWERED;
#else
pdev->dev_config_status = 0U;
#endif
if (pdev->dev_remote_wakeup != 0U)
{
pdev->dev_config_status |= USB_CONFIG_REMOTE_WAKEUP;
}
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_config_status, 2U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
/**
* @brief USBD_SetFeature
* Handle Set device feature request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_SetFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
if (req->wValue == USB_FEATURE_REMOTE_WAKEUP)
{
pdev->dev_remote_wakeup = 1U;
(void)USBD_CtlSendStatus(pdev);
}
}
/**
* @brief USBD_ClrFeature
* Handle clear device feature request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_ClrFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_REMOTE_WAKEUP)
{
pdev->dev_remote_wakeup = 0U;
(void)USBD_CtlSendStatus(pdev);
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
/**
* @brief USBD_ParseSetupRequest
* Copy buffer into setup structure
* @param pdev: device instance
* @param req: usb request
* @retval None
*/
void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata)
{
uint8_t *pbuff = pdata;
req->bmRequest = *(uint8_t *)(pbuff);
pbuff++;
req->bRequest = *(uint8_t *)(pbuff);
pbuff++;
req->wValue = SWAPBYTE(pbuff);
pbuff++;
pbuff++;
req->wIndex = SWAPBYTE(pbuff);
pbuff++;
pbuff++;
req->wLength = SWAPBYTE(pbuff);
}
/**
* @brief USBD_CtlError
* Handle USB low level Error
* @param pdev: device instance
* @param req: usb request
* @retval None
*/
void USBD_CtlError(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
UNUSED(req);
(void)USBD_LL_StallEP(pdev, 0x80U);
(void)USBD_LL_StallEP(pdev, 0U);
}
/**
* @brief USBD_GetString
* Convert Ascii string into unicode one
* @param desc : descriptor buffer
* @param unicode : Formatted string buffer (unicode)
* @param len : descriptor length
* @retval None
*/
void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len)
{
uint8_t idx = 0U;
uint8_t *pdesc;
if (desc == NULL)
{
return;
}
pdesc = desc;
*len = ((uint16_t)USBD_GetLen(pdesc) * 2U) + 2U;
unicode[idx] = *(uint8_t *)len;
idx++;
unicode[idx] = USB_DESC_TYPE_STRING;
idx++;
while (*pdesc != (uint8_t)'\0')
{
unicode[idx] = *pdesc;
pdesc++;
idx++;
unicode[idx] = 0U;
idx++;
}
}
/**
* @brief USBD_GetLen
* return the string length
* @param buf : pointer to the ascii string buffer
* @retval string length
*/
static uint8_t USBD_GetLen(uint8_t *buf)
{
uint8_t len = 0U;
uint8_t *pbuff = buf;
while (*pbuff != (uint8_t)'\0')
{
len++;
pbuff++;
}
return len;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,226 +0,0 @@
/**
******************************************************************************
* @file usbd_ioreq.c
* @author MCD Application Team
* @brief This file provides the IO requests APIs for control endpoints.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_IOREQ
* @brief control I/O requests module
* @{
*/
/** @defgroup USBD_IOREQ_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Functions
* @{
*/
/**
* @brief USBD_CtlSendData
* send data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be sent
* @retval status
*/
USBD_StatusTypeDef USBD_CtlSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_DATA_IN;
pdev->ep_in[0].total_length = len;
#ifdef USBD_AVOID_PACKET_SPLIT_MPS
pdev->ep_in[0].rem_length = 0U;
#else
pdev->ep_in[0].rem_length = len;
#endif
/* Start the transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlContinueSendData
* continue sending data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be sent
* @retval status
*/
USBD_StatusTypeDef USBD_CtlContinueSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Start the next transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlPrepareRx
* receive data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be received
* @retval status
*/
USBD_StatusTypeDef USBD_CtlPrepareRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_DATA_OUT;
pdev->ep_out[0].total_length = len;
#ifdef USBD_AVOID_PACKET_SPLIT_MPS
pdev->ep_out[0].rem_length = 0U;
#else
pdev->ep_out[0].rem_length = len;
#endif
/* Start the transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlContinueRx
* continue receive data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be received
* @retval status
*/
USBD_StatusTypeDef USBD_CtlContinueRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
(void)USBD_LL_PrepareReceive(pdev, 0U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlSendStatus
* send zero lzngth packet on the ctl pipe
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_CtlSendStatus(USBD_HandleTypeDef *pdev)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_STATUS_IN;
/* Start the transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, NULL, 0U);
return USBD_OK;
}
/**
* @brief USBD_CtlReceiveStatus
* receive zero lzngth packet on the ctl pipe
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_CtlReceiveStatus(USBD_HandleTypeDef *pdev)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_STATUS_OUT;
/* Start the transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
return USBD_OK;
}
/**
* @brief USBD_GetRxCount
* returns the received data length
* @param pdev: device instance
* @param ep_addr: endpoint address
* @retval Rx Data blength
*/
uint32_t USBD_GetRxCount(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
return USBD_LL_GetRxDataSize(pdev, ep_addr);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@ -1,97 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usb_device.c
* @version : v3.0_Cube
* @brief : This file implements the USB Device
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usb_device.h"
#include "usbd_core.h"
#include "usbd_desc.h"
#include "usbd_cdc.h"
#include "usbd_cdc_if.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE END PFP */
extern void Error_Handler(void);
/* USB Device Core handle declaration. */
USBD_HandleTypeDef hUsbDeviceFS;
extern USBD_DescriptorsTypeDef CDC_Desc;
/*
* -- Insert your variables declaration here --
*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*
* -- Insert your external function declaration here --
*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Init USB device Library, add supported class and start the library
* @retval None
*/
void MX_USB_Device_Init(void)
{
/* USER CODE BEGIN USB_Device_Init_PreTreatment */
/* USER CODE END USB_Device_Init_PreTreatment */
/* Init Device Library, add supported class and start the library. */
if (USBD_Init(&hUsbDeviceFS, &CDC_Desc, DEVICE_FS) != USBD_OK) {
Error_Handler();
}
if (USBD_RegisterClass(&hUsbDeviceFS, &USBD_CDC) != USBD_OK) {
Error_Handler();
}
if (USBD_CDC_RegisterInterface(&hUsbDeviceFS, &USBD_Interface_fops_FS) != USBD_OK) {
Error_Handler();
}
if (USBD_Start(&hUsbDeviceFS) != USBD_OK) {
Error_Handler();
}
/* USER CODE BEGIN USB_Device_Init_PostTreatment */
/* USER CODE END USB_Device_Init_PostTreatment */
}
/**
* @}
*/
/**
* @}
*/

View File

@ -1,103 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usb_device.h
* @version : v3.0_Cube
* @brief : Header for usb_device.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_DEVICE__H__
#define __USB_DEVICE__H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx.h"
#include "stm32g4xx_hal.h"
#include "usbd_def.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/** @addtogroup USBD_OTG_DRIVER
* @{
*/
/** @defgroup USBD_DEVICE USBD_DEVICE
* @brief Device file for Usb otg low level driver.
* @{
*/
/** @defgroup USBD_DEVICE_Exported_Variables USBD_DEVICE_Exported_Variables
* @brief Public variables.
* @{
*/
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/*
* -- Insert your variables declaration here --
*/
/* USER CODE BEGIN VARIABLES */
/* USER CODE END VARIABLES */
/**
* @}
*/
/** @defgroup USBD_DEVICE_Exported_FunctionsPrototype USBD_DEVICE_Exported_FunctionsPrototype
* @brief Declaration of public functions for Usb device.
* @{
*/
/** USB Device initialization function. */
void MX_USB_Device_Init(void);
/*
* -- Insert functions declaration here --
*/
/* USER CODE BEGIN FD */
/* USER CODE END FD */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_DEVICE__H__ */

View File

@ -1,339 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usbd_cdc_if.c
* @version : v3.0_Cube
* @brief : Usb device for Virtual Com Port.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_if.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @brief Usb device library.
* @{
*/
/** @addtogroup USBD_CDC_IF
* @{
*/
/** @defgroup USBD_CDC_IF_Private_TypesDefinitions USBD_CDC_IF_Private_TypesDefinitions
* @brief Private types.
* @{
*/
/* USER CODE BEGIN PRIVATE_TYPES */
/* USER CODE END PRIVATE_TYPES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Private_Defines USBD_CDC_IF_Private_Defines
* @brief Private defines.
* @{
*/
/* USER CODE BEGIN PRIVATE_DEFINES */
/* USER CODE END PRIVATE_DEFINES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Private_Macros USBD_CDC_IF_Private_Macros
* @brief Private macros.
* @{
*/
/* USER CODE BEGIN PRIVATE_MACRO */
/* USER CODE END PRIVATE_MACRO */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Private_Variables USBD_CDC_IF_Private_Variables
* @brief Private variables.
* @{
*/
/* Create buffer for reception and transmission */
/* It's up to user to redefine and/or remove those define */
/** Received data over USB are stored in this buffer */
uint8_t UserRxBufferFS[APP_RX_DATA_SIZE];
/** Data to send over USB CDC are stored in this buffer */
uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];
/* USER CODE BEGIN PRIVATE_VARIABLES */
/* USER CODE END PRIVATE_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Exported_Variables USBD_CDC_IF_Exported_Variables
* @brief Public variables.
* @{
*/
extern USBD_HandleTypeDef hUsbDeviceFS;
/* USER CODE BEGIN EXPORTED_VARIABLES */
/* USER CODE END EXPORTED_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Private_FunctionPrototypes USBD_CDC_IF_Private_FunctionPrototypes
* @brief Private functions declaration.
* @{
*/
static int8_t CDC_Init_FS(void);
static int8_t CDC_DeInit_FS(void);
static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length);
static int8_t CDC_Receive_FS(uint8_t* pbuf, uint32_t *Len);
static int8_t CDC_TransmitCplt_FS(uint8_t *pbuf, uint32_t *Len, uint8_t epnum);
/* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */
/* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */
/**
* @}
*/
USBD_CDC_ItfTypeDef USBD_Interface_fops_FS =
{
CDC_Init_FS,
CDC_DeInit_FS,
CDC_Control_FS,
CDC_Receive_FS,
CDC_TransmitCplt_FS
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the CDC media low layer over the FS USB IP
* @retval USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_Init_FS(void)
{
/* USER CODE BEGIN 3 */
/* Set Application Buffers */
USBD_CDC_SetTxBuffer(&hUsbDeviceFS, UserTxBufferFS, 0);
USBD_CDC_SetRxBuffer(&hUsbDeviceFS, UserRxBufferFS);
return (USBD_OK);
/* USER CODE END 3 */
}
/**
* @brief DeInitializes the CDC media low layer
* @retval USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_DeInit_FS(void)
{
/* USER CODE BEGIN 4 */
return (USBD_OK);
/* USER CODE END 4 */
}
/**
* @brief Manage the CDC class requests
* @param cmd: Command code
* @param pbuf: Buffer containing command data (request parameters)
* @param length: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length)
{
/* USER CODE BEGIN 5 */
switch(cmd)
{
case CDC_SEND_ENCAPSULATED_COMMAND:
break;
case CDC_GET_ENCAPSULATED_RESPONSE:
break;
case CDC_SET_COMM_FEATURE:
break;
case CDC_GET_COMM_FEATURE:
break;
case CDC_CLEAR_COMM_FEATURE:
break;
/*******************************************************************************/
/* Line Coding Structure */
/*-----------------------------------------------------------------------------*/
/* Offset | Field | Size | Value | Description */
/* 0 | dwDTERate | 4 | Number |Data terminal rate, in bits per second*/
/* 4 | bCharFormat | 1 | Number | Stop bits */
/* 0 - 1 Stop bit */
/* 1 - 1.5 Stop bits */
/* 2 - 2 Stop bits */
/* 5 | bParityType | 1 | Number | Parity */
/* 0 - None */
/* 1 - Odd */
/* 2 - Even */
/* 3 - Mark */
/* 4 - Space */
/* 6 | bDataBits | 1 | Number Data bits (5, 6, 7, 8 or 16). */
/*******************************************************************************/
case CDC_SET_LINE_CODING:
break;
case CDC_GET_LINE_CODING:
break;
case CDC_SET_CONTROL_LINE_STATE:
break;
case CDC_SEND_BREAK:
break;
default:
break;
}
return (USBD_OK);
/* USER CODE END 5 */
}
/**
* @brief Data received over USB OUT endpoint are sent over CDC interface
* through this function.
*
* @note
* This function will issue a NAK packet on any OUT packet received on
* USB endpoint until exiting this function. If you exit this function
* before transfer is complete on CDC interface (ie. using DMA controller)
* it will result in receiving more data while previous ones are still
* not sent.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
/* USER CODE BEGIN 6 */
USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
USBD_CDC_ReceivePacket(&hUsbDeviceFS);
return (USBD_OK);
/* USER CODE END 6 */
}
/**
* @brief CDC_Transmit_FS
* Data to send over USB IN endpoint are sent over CDC interface
* through this function.
* @note
*
*
* @param Buf: Buffer of data to be sent
* @param Len: Number of data to be sent (in bytes)
* @retval USBD_OK if all operations are OK else USBD_FAIL or USBD_BUSY
*/
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
uint8_t result = USBD_OK;
/* USER CODE BEGIN 7 */
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
if (hcdc->TxState != 0){
return USBD_BUSY;
}
USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
result = USBD_CDC_TransmitPacket(&hUsbDeviceFS);
/* USER CODE END 7 */
return result;
}
/**
* @brief CDC_TransmitCplt_FS
* Data transmitted callback
*
* @note
* This function is IN transfer complete callback used to inform user that
* the submitted Data is successfully sent over USB.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_TransmitCplt_FS(uint8_t *Buf, uint32_t *Len, uint8_t epnum)
{
uint8_t result = USBD_OK;
/* USER CODE BEGIN 13 */
UNUSED(Buf);
UNUSED(Len);
UNUSED(epnum);
/* USER CODE END 13 */
return result;
}
/* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */
#include <stdarg.h>
void usb_printf(const char *format, ...)
{
va_list args;
uint32_t length;
va_start(args, format);
length = vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
va_end(args);
CDC_Transmit_FS(UserTxBufferFS, length);
}
/* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */
/**
* @}
*/
/**
* @}
*/

View File

@ -1,131 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usbd_cdc_if.h
* @version : v3.0_Cube
* @brief : Header for usbd_cdc_if.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CDC_IF_H__
#define __USBD_CDC_IF_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @brief For Usb device.
* @{
*/
/** @defgroup USBD_CDC_IF USBD_CDC_IF
* @brief Usb VCP device module
* @{
*/
/** @defgroup USBD_CDC_IF_Exported_Defines USBD_CDC_IF_Exported_Defines
* @brief Defines.
* @{
*/
/* Define size for the receive and transmit buffer over CDC */
#define APP_RX_DATA_SIZE 1024
#define APP_TX_DATA_SIZE 1024
/* USER CODE BEGIN EXPORTED_DEFINES */
/* USER CODE END EXPORTED_DEFINES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Exported_Types USBD_CDC_IF_Exported_Types
* @brief Types.
* @{
*/
/* USER CODE BEGIN EXPORTED_TYPES */
/* USER CODE END EXPORTED_TYPES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Exported_Macros USBD_CDC_IF_Exported_Macros
* @brief Aliases.
* @{
*/
/* USER CODE BEGIN EXPORTED_MACRO */
/* USER CODE END EXPORTED_MACRO */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Exported_Variables USBD_CDC_IF_Exported_Variables
* @brief Public variables.
* @{
*/
/** CDC Interface callback. */
extern USBD_CDC_ItfTypeDef USBD_Interface_fops_FS;
/* USER CODE BEGIN EXPORTED_VARIABLES */
/* USER CODE END EXPORTED_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_CDC_IF_Exported_FunctionsPrototype USBD_CDC_IF_Exported_FunctionsPrototype
* @brief Public functions declaration.
* @{
*/
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len);
/* USER CODE BEGIN EXPORTED_FUNCTIONS */
void usb_printf(const char *format, ...);
/* USER CODE END EXPORTED_FUNCTIONS */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CDC_IF_H__ */

View File

@ -1,396 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : App/usbd_desc.c
* @version : v3.0_Cube
* @brief : This file implements the USB device descriptors.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usbd_core.h"
#include "usbd_desc.h"
#include "usbd_conf.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @{
*/
/** @addtogroup USBD_DESC
* @{
*/
/** @defgroup USBD_DESC_Private_TypesDefinitions USBD_DESC_Private_TypesDefinitions
* @brief Private types.
* @{
*/
/* USER CODE BEGIN PRIVATE_TYPES */
/* USER CODE END PRIVATE_TYPES */
/**
* @}
*/
/** @defgroup USBD_DESC_Private_Defines USBD_DESC_Private_Defines
* @brief Private defines.
* @{
*/
#define USBD_VID 1155
#define USBD_LANGID_STRING 1033
#define USBD_MANUFACTURER_STRING "STMicroelectronics"
#define USBD_PID 22336
#define USBD_PRODUCT_STRING "STM32 Virtual ComPort"
#define USBD_CONFIGURATION_STRING "CDC Config"
#define USBD_INTERFACE_STRING "CDC Interface"
/* USER CODE BEGIN PRIVATE_DEFINES */
/* USER CODE END PRIVATE_DEFINES */
/**
* @}
*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/** @defgroup USBD_DESC_Private_Macros USBD_DESC_Private_Macros
* @brief Private macros.
* @{
*/
/* USER CODE BEGIN PRIVATE_MACRO */
/* USER CODE END PRIVATE_MACRO */
/**
* @}
*/
/** @defgroup USBD_DESC_Private_FunctionPrototypes USBD_DESC_Private_FunctionPrototypes
* @brief Private functions declaration.
* @{
*/
static void Get_SerialNum(void);
static void IntToUnicode(uint32_t value, uint8_t * pbuf, uint8_t len);
/**
* @}
*/
/** @defgroup USBD_DESC_Private_FunctionPrototypes USBD_DESC_Private_FunctionPrototypes
* @brief Private functions declaration.
* @{
*/
uint8_t * USBD_CDC_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t * USBD_CDC_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
/**
* @}
*/
/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables
* @brief Private variables.
* @{
*/
USBD_DescriptorsTypeDef CDC_Desc =
{
USBD_CDC_DeviceDescriptor,
USBD_CDC_LangIDStrDescriptor,
USBD_CDC_ManufacturerStrDescriptor,
USBD_CDC_ProductStrDescriptor,
USBD_CDC_SerialStrDescriptor,
USBD_CDC_ConfigStrDescriptor,
USBD_CDC_InterfaceStrDescriptor
};
#if defined ( __ICCARM__ ) /* IAR Compiler */
#pragma data_alignment=4
#endif /* defined ( __ICCARM__ ) */
/** USB standard device descriptor. */
__ALIGN_BEGIN uint8_t USBD_CDC_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END =
{
0x12, /*bLength */
USB_DESC_TYPE_DEVICE, /*bDescriptorType*/
0x00, /*bcdUSB */
0x02,
0x02, /*bDeviceClass*/
0x02, /*bDeviceSubClass*/
0x00, /*bDeviceProtocol*/
USB_MAX_EP0_SIZE, /*bMaxPacketSize*/
LOBYTE(USBD_VID), /*idVendor*/
HIBYTE(USBD_VID), /*idVendor*/
LOBYTE(USBD_PID), /*idProduct*/
HIBYTE(USBD_PID), /*idProduct*/
0x00, /*bcdDevice rel. 2.00*/
0x02,
USBD_IDX_MFC_STR, /*Index of manufacturer string*/
USBD_IDX_PRODUCT_STR, /*Index of product string*/
USBD_IDX_SERIAL_STR, /*Index of serial number string*/
USBD_MAX_NUM_CONFIGURATION /*bNumConfigurations*/
};
/* USB_DeviceDescriptor */
/**
* @}
*/
/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables
* @brief Private variables.
* @{
*/
#if defined ( __ICCARM__ ) /* IAR Compiler */
#pragma data_alignment=4
#endif /* defined ( __ICCARM__ ) */
/** USB lang identifier descriptor. */
__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END =
{
USB_LEN_LANGID_STR_DESC,
USB_DESC_TYPE_STRING,
LOBYTE(USBD_LANGID_STRING),
HIBYTE(USBD_LANGID_STRING)
};
#if defined ( __ICCARM__ ) /* IAR Compiler */
#pragma data_alignment=4
#endif /* defined ( __ICCARM__ ) */
/* Internal string descriptor. */
__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END;
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif
__ALIGN_BEGIN uint8_t USBD_StringSerial[USB_SIZ_STRING_SERIAL] __ALIGN_END = {
USB_SIZ_STRING_SERIAL,
USB_DESC_TYPE_STRING,
};
/**
* @}
*/
/** @defgroup USBD_DESC_Private_Functions USBD_DESC_Private_Functions
* @brief Private functions.
* @{
*/
/**
* @brief Return the device descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = sizeof(USBD_CDC_DeviceDesc);
return USBD_CDC_DeviceDesc;
}
/**
* @brief Return the LangID string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = sizeof(USBD_LangIDDesc);
return USBD_LangIDDesc;
}
/**
* @brief Return the product string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if(speed == 0)
{
USBD_GetString((uint8_t *)USBD_PRODUCT_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_PRODUCT_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Return the manufacturer string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
USBD_GetString((uint8_t *)USBD_MANUFACTURER_STRING, USBD_StrDesc, length);
return USBD_StrDesc;
}
/**
* @brief Return the serial number string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = USB_SIZ_STRING_SERIAL;
/* Update the serial number string descriptor with the data from the unique
* ID */
Get_SerialNum();
/* USER CODE BEGIN USBD_CDC_SerialStrDescriptor */
/* USER CODE END USBD_CDC_SerialStrDescriptor */
return (uint8_t *) USBD_StringSerial;
}
/**
* @brief Return the configuration string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if(speed == USBD_SPEED_HIGH)
{
USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Return the interface string descriptor
* @param speed : Current device speed
* @param length : Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t * USBD_CDC_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if(speed == 0)
{
USBD_GetString((uint8_t *)USBD_INTERFACE_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_INTERFACE_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Create the serial number string descriptor
* @param None
* @retval None
*/
static void Get_SerialNum(void)
{
uint32_t deviceserial0;
uint32_t deviceserial1;
uint32_t deviceserial2;
deviceserial0 = *(uint32_t *) DEVICE_ID1;
deviceserial1 = *(uint32_t *) DEVICE_ID2;
deviceserial2 = *(uint32_t *) DEVICE_ID3;
deviceserial0 += deviceserial2;
if (deviceserial0 != 0)
{
IntToUnicode(deviceserial0, &USBD_StringSerial[2], 8);
IntToUnicode(deviceserial1, &USBD_StringSerial[18], 4);
}
}
/**
* @brief Convert Hex 32Bits value into char
* @param value: value to convert
* @param pbuf: pointer to the buffer
* @param len: buffer length
* @retval None
*/
static void IntToUnicode(uint32_t value, uint8_t * pbuf, uint8_t len)
{
uint8_t idx = 0;
for (idx = 0; idx < len; idx++)
{
if (((value >> 28)) < 0xA)
{
pbuf[2 * idx] = (value >> 28) + '0';
}
else
{
pbuf[2 * idx] = (value >> 28) + 'A' - 10;
}
value = value << 4;
pbuf[2 * idx + 1] = 0;
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/

View File

@ -1,143 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usbd_desc.c
* @version : v3.0_Cube
* @brief : Header for usbd_conf.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_DESC__C__
#define __USBD_DESC__C__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_DESC USBD_DESC
* @brief Usb device descriptors module.
* @{
*/
/** @defgroup USBD_DESC_Exported_Constants USBD_DESC_Exported_Constants
* @brief Constants.
* @{
*/
#define DEVICE_ID1 (UID_BASE)
#define DEVICE_ID2 (UID_BASE + 0x4)
#define DEVICE_ID3 (UID_BASE + 0x8)
#define USB_SIZ_STRING_SERIAL 0x1A
/* USER CODE BEGIN EXPORTED_CONSTANTS */
/* USER CODE END EXPORTED_CONSTANTS */
/**
* @}
*/
/** @defgroup USBD_DESC_Exported_Defines USBD_DESC_Exported_Defines
* @brief Defines.
* @{
*/
/* USER CODE BEGIN EXPORTED_DEFINES */
/* USER CODE END EXPORTED_DEFINES */
/**
* @}
*/
/** @defgroup USBD_DESC_Exported_TypesDefinitions USBD_DESC_Exported_TypesDefinitions
* @brief Types.
* @{
*/
/* USER CODE BEGIN EXPORTED_TYPES */
/* USER CODE END EXPORTED_TYPES */
/**
* @}
*/
/** @defgroup USBD_DESC_Exported_Macros USBD_DESC_Exported_Macros
* @brief Aliases.
* @{
*/
/* USER CODE BEGIN EXPORTED_MACRO */
/* USER CODE END EXPORTED_MACRO */
/**
* @}
*/
/** @defgroup USBD_DESC_Exported_Variables USBD_DESC_Exported_Variables
* @brief Public variables.
* @{
*/
extern USBD_DescriptorsTypeDef CDC_Desc;
/* USER CODE BEGIN EXPORTED_VARIABLES */
/* USER CODE END EXPORTED_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_DESC_Exported_FunctionsPrototype USBD_DESC_Exported_FunctionsPrototype
* @brief Public functions declaration.
* @{
*/
/* USER CODE BEGIN EXPORTED_FUNCTIONS */
/* USER CODE END EXPORTED_FUNCTIONS */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_DESC__C__ */

View File

@ -1,797 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : Target/usbd_conf.c
* @version : v3.0_Cube
* @brief : This file implements the board support package for the USB device library
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx.h"
#include "stm32g4xx_hal.h"
#include "usbd_def.h"
#include "usbd_core.h"
#include "usbd_cdc.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
PCD_HandleTypeDef hpcd_USB_FS;
void Error_Handler(void);
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* Exported function prototypes ----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE END PFP */
/* Private functions ---------------------------------------------------------*/
static USBD_StatusTypeDef USBD_Get_USB_Status(HAL_StatusTypeDef hal_status);
/* USER CODE BEGIN 1 */
static void SystemClockConfig_Resume(void);
/* USER CODE END 1 */
extern void SystemClock_Config(void);
/*******************************************************************************
LL Driver Callbacks (PCD -> USB Device Library)
*******************************************************************************/
/* MSP Init */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle)
#else
void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(pcdHandle->Instance==USB)
{
/* USER CODE BEGIN USB_MspInit 0 */
/* USER CODE END USB_MspInit 0 */
/** Initializes the peripherals clocks
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_HSI48;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_USB_CLK_ENABLE();
/* Peripheral interrupt init */
HAL_NVIC_SetPriority(USB_LP_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USB_LP_IRQn);
/* USER CODE BEGIN USB_MspInit 1 */
/* USER CODE END USB_MspInit 1 */
}
}
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle)
#else
void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
if(pcdHandle->Instance==USB)
{
/* USER CODE BEGIN USB_MspDeInit 0 */
/* USER CODE END USB_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USB_CLK_DISABLE();
/* Peripheral interrupt Deinit*/
HAL_NVIC_DisableIRQ(USB_LP_IRQn);
/* USER CODE BEGIN USB_MspDeInit 1 */
/* USER CODE END USB_MspDeInit 1 */
}
}
/**
* @brief Setup stage callback
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_SetupStageCallback_PreTreatment */
/* USER CODE END HAL_PCD_SetupStageCallback_PreTreatment */
USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t *)hpcd->Setup);
/* USER CODE BEGIN HAL_PCD_SetupStageCallback_PostTreatment */
/* USER CODE END HAL_PCD_SetupStageCallback_PostTreatment */
}
/**
* @brief Data Out stage callback.
* @param hpcd: PCD handle
* @param epnum: Endpoint number
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#else
void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_DataOutStageCallback_PreTreatment */
/* USER CODE END HAL_PCD_DataOutStageCallback_PreTreatment */
USBD_LL_DataOutStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->OUT_ep[epnum].xfer_buff);
/* USER CODE BEGIN HAL_PCD_DataOutStageCallback_PostTreatment */
/* USER CODE END HAL_PCD_DataOutStageCallback_PostTreatment */
}
/**
* @brief Data In stage callback.
* @param hpcd: PCD handle
* @param epnum: Endpoint number
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#else
void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_DataInStageCallback_PreTreatment */
/* USER CODE END HAL_PCD_DataInStageCallback_PreTreatment */
USBD_LL_DataInStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->IN_ep[epnum].xfer_buff);
/* USER CODE BEGIN HAL_PCD_DataInStageCallback_PostTreatment */
/* USER CODE END HAL_PCD_DataInStageCallback_PostTreatment */
}
/**
* @brief SOF callback.
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_SOFCallback_PreTreatment */
/* USER CODE END HAL_PCD_SOFCallback_PreTreatment */
USBD_LL_SOF((USBD_HandleTypeDef*)hpcd->pData);
/* USER CODE BEGIN HAL_PCD_SOFCallback_PostTreatment */
/* USER CODE END HAL_PCD_SOFCallback_PostTreatment */
}
/**
* @brief Reset callback.
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_ResetCallback_PreTreatment */
/* USER CODE END HAL_PCD_ResetCallback_PreTreatment */
USBD_SpeedTypeDef speed = USBD_SPEED_FULL;
if ( hpcd->Init.speed != PCD_SPEED_FULL)
{
Error_Handler();
}
/* Set Speed. */
USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed);
/* Reset Device. */
USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData);
/* USER CODE BEGIN HAL_PCD_ResetCallback_PostTreatment */
/* USER CODE END HAL_PCD_ResetCallback_PostTreatment */
}
/**
* @brief Suspend callback.
* When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it)
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_SuspendCallback_PreTreatment */
/* USER CODE END HAL_PCD_SuspendCallback_PreTreatment */
/* Inform USB library that core enters in suspend Mode. */
USBD_LL_Suspend((USBD_HandleTypeDef*)hpcd->pData);
/* Enter in STOP mode. */
/* USER CODE BEGIN 2 */
if (hpcd->Init.low_power_enable)
{
/* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register. */
SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
}
/* USER CODE END 2 */
/* USER CODE BEGIN HAL_PCD_SuspendCallback_PostTreatment */
/* USER CODE END HAL_PCD_SuspendCallback_PostTreatment */
}
/**
* @brief Resume callback.
* When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it)
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_ResumeCallback_PreTreatment */
/* USER CODE END HAL_PCD_ResumeCallback_PreTreatment */
/* USER CODE BEGIN 3 */
if (hpcd->Init.low_power_enable)
{
/* Reset SLEEPDEEP bit of Cortex System Control Register. */
SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
SystemClockConfig_Resume();
}
/* USER CODE END 3 */
USBD_LL_Resume((USBD_HandleTypeDef*)hpcd->pData);
/* USER CODE BEGIN HAL_PCD_ResumeCallback_PostTreatment */
/* USER CODE END HAL_PCD_ResumeCallback_PostTreatment */
}
/**
* @brief ISOOUTIncomplete callback.
* @param hpcd: PCD handle
* @param epnum: Endpoint number
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#else
void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_ISOOUTIncompleteCallback_PreTreatment */
/* USER CODE END HAL_PCD_ISOOUTIncompleteCallback_PreTreatment */
USBD_LL_IsoOUTIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum);
/* USER CODE BEGIN HAL_PCD_ISOOUTIncompleteCallback_PostTreatment */
/* USER CODE END HAL_PCD_ISOOUTIncompleteCallback_PostTreatment */
}
/**
* @brief ISOINIncomplete callback.
* @param hpcd: PCD handle
* @param epnum: Endpoint number
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#else
void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_ISOINIncompleteCallback_PreTreatment */
/* USER CODE END HAL_PCD_ISOINIncompleteCallback_PreTreatment */
USBD_LL_IsoINIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum);
/* USER CODE BEGIN HAL_PCD_ISOINIncompleteCallback_PostTreatment */
/* USER CODE END HAL_PCD_ISOINIncompleteCallback_PostTreatment */
}
/**
* @brief Connect callback.
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_ConnectCallback_PreTreatment */
/* USER CODE END HAL_PCD_ConnectCallback_PreTreatment */
USBD_LL_DevConnected((USBD_HandleTypeDef*)hpcd->pData);
/* USER CODE BEGIN HAL_PCD_ConnectCallback_PostTreatment */
/* USER CODE END HAL_PCD_ConnectCallback_PostTreatment */
}
/**
* @brief Disconnect callback.
* @param hpcd: PCD handle
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
#else
void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN HAL_PCD_DisconnectCallback_PreTreatment */
/* USER CODE END HAL_PCD_DisconnectCallback_PreTreatment */
USBD_LL_DevDisconnected((USBD_HandleTypeDef*)hpcd->pData);
/* USER CODE BEGIN HAL_PCD_DisconnectCallback_PostTreatment */
/* USER CODE END HAL_PCD_DisconnectCallback_PostTreatment */
}
/* USER CODE BEGIN LowLevelInterface */
/* USER CODE END LowLevelInterface */
/*******************************************************************************
LL Driver Interface (USB Device Library --> PCD)
*******************************************************************************/
/**
* @brief Initializes the low level portion of the device driver.
* @param pdev: Device handle
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev)
{
/* Init USB Ip. */
hpcd_USB_FS.pData = pdev;
/* Link the driver to the stack. */
pdev->pData = &hpcd_USB_FS;
hpcd_USB_FS.Instance = USB;
hpcd_USB_FS.Init.dev_endpoints = 8;
hpcd_USB_FS.Init.speed = PCD_SPEED_FULL;
hpcd_USB_FS.Init.phy_itface = PCD_PHY_EMBEDDED;
hpcd_USB_FS.Init.Sof_enable = DISABLE;
hpcd_USB_FS.Init.low_power_enable = DISABLE;
hpcd_USB_FS.Init.lpm_enable = DISABLE;
hpcd_USB_FS.Init.battery_charging_enable = DISABLE;
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
/* register Msp Callbacks (before the Init) */
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_MSPINIT_CB_ID, PCD_MspInit);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_MSPDEINIT_CB_ID, PCD_MspDeInit);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
if (HAL_PCD_Init(&hpcd_USB_FS) != HAL_OK)
{
Error_Handler( );
}
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
/* Register USB PCD CallBacks */
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_SOF_CB_ID, PCD_SOFCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_SETUPSTAGE_CB_ID, PCD_SetupStageCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_RESET_CB_ID, PCD_ResetCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_SUSPEND_CB_ID, PCD_SuspendCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_RESUME_CB_ID, PCD_ResumeCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_CONNECT_CB_ID, PCD_ConnectCallback);
HAL_PCD_RegisterCallback(&hpcd_USB_FS, HAL_PCD_DISCONNECT_CB_ID, PCD_DisconnectCallback);
/* USER CODE BEGIN RegisterCallBackFirstPart */
/* USER CODE END RegisterCallBackFirstPart */
HAL_PCD_RegisterLpmCallback(&hpcd_USB_FS, PCDEx_LPM_Callback);
HAL_PCD_RegisterDataOutStageCallback(&hpcd_USB_FS, PCD_DataOutStageCallback);
HAL_PCD_RegisterDataInStageCallback(&hpcd_USB_FS, PCD_DataInStageCallback);
HAL_PCD_RegisterIsoOutIncpltCallback(&hpcd_USB_FS, PCD_ISOOUTIncompleteCallback);
HAL_PCD_RegisterIsoInIncpltCallback(&hpcd_USB_FS, PCD_ISOINIncompleteCallback);
/* USER CODE BEGIN RegisterCallBackSecondPart */
/* USER CODE END RegisterCallBackSecondPart */
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
/* USER CODE BEGIN EndPoint_Configuration */
HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x00 , PCD_SNG_BUF, 0x18);
HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x80 , PCD_SNG_BUF, 0x58);
/* USER CODE END EndPoint_Configuration */
/* USER CODE BEGIN EndPoint_Configuration_CDC */
HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x81 , PCD_SNG_BUF, 0xC0);
HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x01 , PCD_SNG_BUF, 0x110);
HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x82 , PCD_SNG_BUF, 0x100);
/* USER CODE END EndPoint_Configuration_CDC */
return USBD_OK;
}
/**
* @brief De-Initializes the low level portion of the device driver.
* @param pdev: Device handle
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_DeInit(pdev->pData);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Starts the low level portion of the device driver.
* @param pdev: Device handle
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_Start(pdev->pData);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Stops the low level portion of the device driver.
* @param pdev: Device handle
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_Stop(pdev->pData);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Opens an endpoint of the low level driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @param ep_type: Endpoint type
* @param ep_mps: Endpoint max packet size
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t ep_type, uint16_t ep_mps)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_Open(pdev->pData, ep_addr, ep_mps, ep_type);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Closes an endpoint of the low level driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_Close(pdev->pData, ep_addr);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Flushes an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_Flush(pdev->pData, ep_addr);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Sets a Stall condition on an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_SetStall(pdev->pData, ep_addr);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Clears a Stall condition on an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_ClrStall(pdev->pData, ep_addr);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Returns Stall condition.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval Stall (1: Yes, 0: No)
*/
uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*) pdev->pData;
if((ep_addr & 0x80) == 0x80)
{
return hpcd->IN_ep[ep_addr & 0x7F].is_stall;
}
else
{
return hpcd->OUT_ep[ep_addr & 0x7F].is_stall;
}
}
/**
* @brief Assigns a USB address to the device.
* @param pdev: Device handle
* @param dev_addr: Device address
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev, uint8_t dev_addr)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_SetAddress(pdev->pData, dev_addr);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Transmits data over an endpoint.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @param pbuf: Pointer to data to be sent
* @param size: Data size
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_Transmit(pdev->pData, ep_addr, pbuf, size);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Prepares an endpoint for reception.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @param pbuf: Pointer to data to be received
* @param size: Data size
* @retval USBD status
*/
USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size)
{
HAL_StatusTypeDef hal_status = HAL_OK;
USBD_StatusTypeDef usb_status = USBD_OK;
hal_status = HAL_PCD_EP_Receive(pdev->pData, ep_addr, pbuf, size);
usb_status = USBD_Get_USB_Status(hal_status);
return usb_status;
}
/**
* @brief Returns the last transferred packet size.
* @param pdev: Device handle
* @param ep_addr: Endpoint number
* @retval Received Data Size
*/
uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
return HAL_PCD_EP_GetRxCount((PCD_HandleTypeDef*) pdev->pData, ep_addr);
}
/**
* @brief Send LPM message to user layer
* @param hpcd: PCD handle
* @param msg: LPM message
* @retval None
*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
static void PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
#else
void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
{
/* USER CODE BEGIN LPM_Callback */
switch (msg)
{
case PCD_LPM_L0_ACTIVE:
if (hpcd->Init.low_power_enable)
{
SystemClockConfig_Resume();
/* Reset SLEEPDEEP bit of Cortex System Control Register. */
SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
}
USBD_LL_Resume(hpcd->pData);
break;
case PCD_LPM_L1_ACTIVE:
USBD_LL_Suspend(hpcd->pData);
/* Enter in STOP mode. */
if (hpcd->Init.low_power_enable)
{
/* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register. */
SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
}
break;
}
/* USER CODE END LPM_Callback */
}
/**
* @brief Delays routine for the USB Device Library.
* @param Delay: Delay in ms
* @retval None
*/
void USBD_LL_Delay(uint32_t Delay)
{
HAL_Delay(Delay);
}
/**
* @brief Static single allocation.
* @param size: Size of allocated memory
* @retval None
*/
void *USBD_static_malloc(uint32_t size)
{
static uint32_t mem[(sizeof(USBD_CDC_HandleTypeDef)/4)+1];/* On 32-bit boundary */
return mem;
}
/**
* @brief Dummy memory free
* @param p: Pointer to allocated memory address
* @retval None
*/
void USBD_static_free(void *p)
{
}
/* USER CODE BEGIN 5 */
/**
* @brief Configures system clock after wake-up from USB resume callBack:
* enable HSI, PLL and select PLL as system clock source.
* @retval None
*/
static void SystemClockConfig_Resume(void)
{
SystemClock_Config();
}
/* USER CODE END 5 */
/**
* @brief Returns the USB status depending on the HAL status:
* @param hal_status: HAL status
* @retval USB status
*/
USBD_StatusTypeDef USBD_Get_USB_Status(HAL_StatusTypeDef hal_status)
{
USBD_StatusTypeDef usb_status = USBD_OK;
switch (hal_status)
{
case HAL_OK :
usb_status = USBD_OK;
break;
case HAL_ERROR :
usb_status = USBD_FAIL;
break;
case HAL_BUSY :
usb_status = USBD_BUSY;
break;
case HAL_TIMEOUT :
usb_status = USBD_FAIL;
break;
default :
usb_status = USBD_FAIL;
break;
}
return usb_status;
}

View File

@ -1,175 +0,0 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : usbd_conf.h
* @version : v3.0_Cube
* @brief : Header for usbd_conf.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CONF__H__
#define __USBD_CONF__H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stm32g4xx.h"
#include "stm32g4xx_hal.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/** @addtogroup USBD_OTG_DRIVER
* @brief Driver for Usb device.
* @{
*/
/** @defgroup USBD_CONF USBD_CONF
* @brief Configuration file for Usb otg low level driver.
* @{
*/
/** @defgroup USBD_CONF_Exported_Variables USBD_CONF_Exported_Variables
* @brief Public variables.
* @{
*/
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Defines USBD_CONF_Exported_Defines
* @brief Defines for configuration of the Usb device.
* @{
*/
/*---------- -----------*/
#define USBD_MAX_NUM_INTERFACES 1U
/*---------- -----------*/
#define USBD_MAX_NUM_CONFIGURATION 1U
/*---------- -----------*/
#define USBD_MAX_STR_DESC_SIZ 512U
/*---------- -----------*/
#define USBD_DEBUG_LEVEL 0U
/*---------- -----------*/
#define USBD_LPM_ENABLED 1U
/*---------- -----------*/
#define USBD_SELF_POWERED 1U
/****************************************/
/* #define for FS and HS identification */
#define DEVICE_FS 0
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Macros USBD_CONF_Exported_Macros
* @brief Aliases.
* @{
*/
/* Memory management macros */
/** Alias for memory allocation. */
#define USBD_malloc (void *)USBD_static_malloc
/** Alias for memory release. */
#define USBD_free USBD_static_free
/** Alias for memory set. */
#define USBD_memset memset
/** Alias for memory copy. */
#define USBD_memcpy memcpy
/** Alias for delay. */
#define USBD_Delay HAL_Delay
/* DEBUG macros */
#if (USBD_DEBUG_LEVEL > 0)
#define USBD_UsrLog(...) printf(__VA_ARGS__);\
printf("\n");
#else
#define USBD_UsrLog(...)
#endif
#if (USBD_DEBUG_LEVEL > 1)
#define USBD_ErrLog(...) printf("ERROR: ") ;\
printf(__VA_ARGS__);\
printf("\n");
#else
#define USBD_ErrLog(...)
#endif
#if (USBD_DEBUG_LEVEL > 2)
#define USBD_DbgLog(...) printf("DEBUG : ") ;\
printf(__VA_ARGS__);\
printf("\n");
#else
#define USBD_DbgLog(...)
#endif
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Types USBD_CONF_Exported_Types
* @brief Types.
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_FunctionsPrototype USBD_CONF_Exported_FunctionsPrototype
* @brief Declaration of public functions for Usb device.
* @{
*/
/* Exported functions -------------------------------------------------------*/
void *USBD_static_malloc(uint32_t size);
void USBD_static_free(void *p);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CONF__H__ */