void SysTickInit() { // Update SystemCoreClock value SystemCoreClockUpdate(); // Configure the SysTick timer to overflow every 1 us SysTick_Config(SystemCoreClock / 1000000); // Anti Trap Process if others irq have higher priority and wait for systick count __NVIC_SetPriority(SysTick_IRQn,0); }

时间: 2025-04-03 09:05:15 AIGC 浏览: 59
<think>好的,我现在需要解释用户提供的这个SysTickInit()函数。首先,我得理解每一行代码的作用,然后组织成清晰的中文解释。 首先,SystemCoreClockUpdate(); 这个函数应该是用来更新系统核心时钟的,可能读取芯片的时钟配置,确保SystemCoreClock变量正确。接下来是SysTick_Config,参数是SystemCoreClock除以1000000,这应该是设置SysTick定时器每1微秒溢出一次,因为1秒等于1,000,000微秒,所以用系统时钟频率除以这个数得到重装载值。然后,设置SysTick中断的优先级为0,这里需要注意NVIC的优先级数值越小优先级越高,所以这里可能是为了提高SysTick的中断优先级,防止其他中断阻塞它。不过用户提到“Anti Trap Process”,可能是指防止其他高优先级中断导致SysTick无法及时响应,所以设置最高优先级(假设0是最高)。需要确认一下Cortex-M的优先级设定,有的系统是数值越低优先级越高,这点正确。然后,用户代码注释提到“Anti Trap Process if others irq have higher priority and wait for systick count”,所以设置优先级为0确保SysTick中断不会被其他中断抢占,避免延迟。最后,整个函数的作用是初始化SysTick定时器,用于精确的延时或定时任务,比如操作系统的时间片调度或者需要微秒级延时的应用。需要检查是否有遗漏的部分,比如是否启用中断,但SysTick_Config通常会自动启用定时器和中断。可能还需要提到SysTick是Cortex-M内核的内置定时器,常用于操作系统的时钟节拍。总结各部分功能,分步骤解释,确保用户明白每个函数调用和设置的目的。</think>以下是 `SysTickInit()` 函数的逐行解析及作用说明: --- ### 1. **系统时钟更新** ```c SystemCoreClockUpdate(); ``` - **功能**:更新 `SystemCoreClock` 全局变量(存储CPU主频值,单位Hz)。 - **必要性**:确保后续代码使用准确的时钟频率(例如芯片从内部RC切换到外部晶振后需重新校准)。 --- ### 2. **配置SysTick定时器** ```c SysTick_Config(SystemCoreClock / 1000000); ``` - **功能**:设置SysTick定时器每 **1微秒** 触发一次中断。 - **参数计算**: - 假设 `SystemCoreClock = 72MHz`,则 `72,000,000 / 1,000,000 = 72`。 - SysTick重装载值(LOAD寄存器)设为72,表示每72个时钟周期触发一次中断。 - **内部行为**: - 自动启用SysTick定时器及其异常请求。 - 选择内核时钟源(通常为处理器时钟,而非分频后的系统时钟)。 --- ### 3. **设置中断优先级** ```c __NVIC_SetPriority(SysTick_IRQn, 0); ``` - **功能**:将SysTick中断优先级设为 **0**(最高优先级)。 - **必要性**: - **防阻塞**:避免其他高优先级中断长时间占用CPU,导致SysTick无法及时响应。 - **实时性保障**:SysTick常用于关键任务(如RTOS时间片调度),需确保中断响应延迟最小。 --- ### 4. **SysTick的典型应用场景** - **精确延时**:通过计数器实现微秒级延时(例如 `delay_us()` 函数)。 - **RTOS心跳**:为操作系统提供周期性时间基准(如FreeRTOS的 `vTaskDelay`)。 - **任务调度**:在多任务系统中管理时间片轮转。 --- ### 5. **注意事项** - **中断服务函数**:需实现 `SysTick_Handler()` 处理中断逻辑(例如更新计数器)。 - **优先级范围**:Cortex-M中优先级数值越小优先级越高,具体范围由芯片厂商定义(如0-15或0-255)。 - **时钟源选择**:部分芯片支持SysTick选择不同的时钟源(需查阅手册确认)。 --- 通过此初始化代码,SysTick定时器将以精确的1微秒间隔运行,为系统提供可靠的时间基准。
阅读全文

相关推荐

/* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ #if defined (__Vendor_SysTickConfig) && (__Vendor_SysTickConfig == 0U) /** \brief System Tick Configuration \details Initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); /* Reload value impossible */ } SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */

/* add user code begin Header */ /** ************************************************************************** * @file at32a423_int.c * @brief main interrupt service routines. ************************************************************************** * Copyright notice & Disclaimer * * The software Board Support Package (BSP) that is made available to * download from Artery official website is the copyrighted work of Artery. * Artery authorizes customers to use, copy, and distribute the BSP * software and its related documentation for the purpose of design and * development in conjunction with Artery microcontrollers. Use of the * software is governed by this copyright notice and the following disclaimer. * * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ************************************************************************** */ /* add user code end Header */ /* includes ------------------------------------------------------------------*/ #include "at32a423_int.h" #include "wk_system.h" volatile uint32_t flow_pulse_count = 0; // 脉冲计数 volatile uint32_t flow_frequency_hz = 0; // 测量频率(Hz) float flow_rate_l_min = 0.0f; // 流量值(L/min) uint32_t last_measure_time = 0;// 上次测量时间戳 static uint32_t interrupt_count = 0; #define FRAME_MAX_LEN 64 // 定义最大帧长度 typedef enum { UART_RX_IDLE = 0, // 空闲状态 UART_RX_RECEIVING, // 接收中状态 UART_RX_COMPLETE // 接收完成状态 } UART_RX_Status; typedef struct { uint8_t buffer[FRAME_MAX_LEN]; // 接收缓冲区 uint16_t index; // 当前接收位置 uint16_t length; // 帧长度 UART_RX_Status status; // 接收状态 uint8_t frameComplete; // 帧接收完成标志 } UART_RX_Handler; UART_RX_Handler uart3_rx; //#define PULSES_PER_LITER 450 // 每升水对应的脉冲数 //#define MEASURE_INTERVAL 1000 // 测量间隔(ms) /* private includes ----------------------------------------------------------*/ /* add user code begin private includes */ /* add user code end private includes */ /* private typedef -----------------------------------------------------------*/ /* add user code begin private typedef */ /* add user code end private typedef */ /* private define ------------------------------------------------------------*/ /* add user code begin private define */ /* add user code end private define */ /* private macro -------------------------------------------------------------*/ /* add user code begin private macro */ /* add user code end private macro */ /* private variables ---------------------------------------------------------*/ /* add user code begin private variables */ /* add user code end private variables */ /* private function prototypes --------------------------------------------*/ /* add user code begin function prototypes */ /* add user code end function prototypes */ /* private user code ---------------------------------------------------------*/ /* add user code begin 0 */ /* add user code end 0 */ /* external variables ---------------------------------------------------------*/ /* add user code begin external variables */ /* add user code end external variables */ /** * @brief this function handles nmi exception. * @param none * @retval none */ void NMI_Handler(void) { /* add user code begin NonMaskableInt_IRQ 0 */ /* add user code end NonMaskableInt_IRQ 0 */ /* add user code begin NonMaskableInt_IRQ 1 */ /* add user code end NonMaskableInt_IRQ 1 */ } /** * @brief this function handles hard fault exception. * @param none * @retval none */ void HardFault_Handler(void) { /* add user code begin HardFault_IRQ 0 */ /* add user code end HardFault_IRQ 0 */ /* go to infinite loop when hard fault exception occurs */ while (1) { /* add user code begin W1_HardFault_IRQ 0 */ /* add user code end W1_HardFault_IRQ 0 */ } } /** * @brief this function handles memory manage exception. * @param none * @retval none */ void MemManage_Handler(void) { /* add user code begin MemoryManagement_IRQ 0 */ /* add user code end MemoryManagement_IRQ 0 */ /* go to infinite loop when memory manage exception occurs */ while (1) { /* add user code begin W1_MemoryManagement_IRQ 0 */ /* add user code end W1_MemoryManagement_IRQ 0 */ } } /** * @brief this function handles bus fault exception. * @param none * @retval none */ void BusFault_Handler(void) { /* add user code begin BusFault_IRQ 0 */ /* add user code end BusFault_IRQ 0 */ /* go to infinite loop when bus fault exception occurs */ while (1) { /* add user code begin W1_BusFault_IRQ 0 */ /* add user code end W1_BusFault_IRQ 0 */ } } /** * @brief this function handles usage fault exception. * @param none * @retval none */ void UsageFault_Handler(void) { /* add user code begin UsageFault_IRQ 0 */ /* add user code end UsageFault_IRQ 0 */ /* go to infinite loop when usage fault exception occurs */ while (1) { /* add user code begin W1_UsageFault_IRQ 0 */ /* add user code end W1_UsageFault_IRQ 0 */ } } /** * @brief this function handles svcall exception. * @param none * @retval none */ void SVC_Handler(void) { /* add user code begin SVCall_IRQ 0 */ /* add user code end SVCall_IRQ 0 */ /* add user code begin SVCall_IRQ 1 */ /* add user code end SVCall_IRQ 1 */ } /** * @brief this function handles debug monitor exception. * @param none * @retval none */ void DebugMon_Handler(void) { /* add user code begin DebugMonitor_IRQ 0 */ /* add user code end DebugMonitor_IRQ 0 */ /* add user code begin DebugMonitor_IRQ 1 */ /* add user code end DebugMonitor_IRQ 1 */ } /** * @brief this function handles pendsv_handler exception. * @param none * @retval none */ void PendSV_Handler(void) { /* add user code begin PendSV_IRQ 0 */ /* add user code end PendSV_IRQ 0 */ /* add user code begin PendSV_IRQ 1 */ /* add user code end PendSV_IRQ 1 */ } /** * @brief this function handles systick handler. * @param none * @retval none */ void SysTick_Handler(void) { /* add user code begin SysTick_IRQ 0 */ /* add user code end SysTick_IRQ 0 */ wk_timebase_handler(); /* add user code begin SysTick_IRQ 1 */ /* add user code end SysTick_IRQ 1 */ } /** * @brief this function handles ADC1 handler. * @param none * @retval none */ void ADC1_IRQHandler(void) { /* add user code begin ADC1_IRQ 0 */ /* add user code end ADC1_IRQ 0 */ /* add user code begin ADC1_IRQ 1 */ /* add user code end ADC1_IRQ 1 */ } void USART3_IRQHandler(void) { /* add user code begin USART1_IRQ 0 */ uint16_t reval; // time_ira_cnt = 0; /* clear upgrade time out flag */ if(usart_flag_get(USART3, USART_RDBF_FLAG) != RESET) { reval = usart_data_receive(USART3); if(reval == 0x5A&& uart3_rx.status == UART_RX_IDLE) //帧头5A { uart3_rx.status = UART_RX_RECEIVING; uart3_rx.index = 0; uart3_rx.buffer[uart3_rx.index++] = reval; } else if(uart3_rx.status == UART_RX_RECEIVING) { // 保存接收到的 uart3_rx.buffer[uart3_rx.index++] = reval; // 帧尾检测 (假设帧尾是0xA5) if(reval == 0xA5) { uart3_rx.length = uart3_rx.index; uart3_rx.status = UART_RX_COMPLETE; uart3_rx.frameComplete = 1; } // 检查是否超出最大长度 else if(uart3_rx.index >= FRAME_MAX_LEN) { uart3_rx.status = UART_RX_IDLE; uart3_rx.index = 0; } } } /* add user code end USART1_IRQ 0 */ /* add user code begin USART1_IRQ 1 */ if(usart_flag_get(USART3, USART_RDBF_FLAG) != RESET) { usart_flag_clear(USART3, USART_RDBF_FLAG); } /* add user code end USART1_IRQ 1 */ } void Process_UART_Frame(void) { // int i; if(uart3_rx.frameComplete) { uint8_t amd; // 解析帧数据 // 示例:假设帧格式为 [0xAA][命令][数据1][数据2]...[0x55] amd = uart3_rx.buffer[1]; // 命令字节 switch(amd) { case 0x03: // 处理03命令 if(uart3_rx.buffer[0] == 0x5A && uart3_rx.buffer[2] == 0xA5) { Send_FlowData_To_USART3(); // 发送流量数据 } break; // case 13:Trigger_Usart_Read(USART_TARGET_2);break; // case 23:Trigger_Usart_Read(USART_TARGET_1);break; // case 33:Trigger_Usart_Read(USART_TARGET_5);break; // case 43: Send_Feedback_Frame(0x03);break; } // 处理完成后重置接收状态 uart3_rx.frameComplete = 0; uart3_rx.status = UART_RX_IDLE; uart3_rx.index = 0; // buffer_position = 0; // 重新启动接收 } } /* add user code begin 1 */ //gpio_init_type gpio_init_struct = {0}; //crm_clocks_freq_type crm_clocks_freq_struct = {0}; //tmr_input_config_type tmr_input_config_struct; //void delay(uint32_t time); //void uart_init(uint32_t bound); //__IO uint32_t tmr3freq = 0; //__IO uint32_t sys_counter = 0; __IO uint16_t capture_count = 0; __IO uint16_t first_capture = 0, second_capture = 0; __IO uint32_t capture_value = 0; volatile uint32_t overflow_count = 0; // 软件溢出计数器 /* add user code end 1 */ void TMR2_IRQHandler(void) { if (tmr_interrupt_flag_get(TMR2, TMR_C1_FLAG) == SET) { tmr_flag_clear(TMR2, TMR_C1_FLAG); if (capture_count == 0) { first_capture = tmr_channel_value_get(TMR2, TMR_SELECT_CHANNEL_1); capture_count = 1; } else { second_capture = tmr_channel_value_get(TMR2, TMR_SELECT_CHANNEL_1); if (second_capture > first_capture) { capture_value = second_capture - first_capture; } else { capture_value = (0xFFFF - first_capture) + second_capture; } if (capture_value > 0) { uint32_t timer_freq = 24000000; // 假设TMR2时钟为24MHz flow_frequency_hz = timer_freq / capture_value; flow_pulse_count ++; // 每个完整周期计数一次 } capture_count = 0; } } } void TMR2_GLOBAL_IRQHandler(void) { // interrupt_count++; if (tmr_interrupt_flag_get(TMR2, TMR_OVF_FLAG) == SET) { tmr_flag_clear(TMR2, TMR_OVF_FLAG); // 清除溢出标志 overflow_count++; // 溢出次数加1 } if (tmr_interrupt_flag_get(TMR2, TMR_C1_FLAG) == SET) { // 通过串口输出调试信息 tmr_flag_clear(TMR2, TMR_C1_FLAG); flow_pulse_count ++; } } void Calculate_FlowRate(void) { static uint32_t last_pulse_count = 0; uint32_t pulses_in_interval; // 计算时间间隔内的脉冲数 pulses_in_interval = flow_pulse_count - last_pulse_count; last_pulse_count = flow_pulse_count; // 计算频率 (Hz) flow_frequency_hz = (pulses_in_interval * 1000) / MEASURE_INTERVAL; // 计算流量 (L/min) = (脉冲数/脉冲每升) × (60/时间间隔秒) flow_rate_l_min = (pulses_in_interval / (float)PULSES_PER_LITER) * (60.0f / (MEASURE_INTERVAL / 1000.0f)); } void Send_FlowData_To_USART3(void) { uint8_t tx_buffer[10]; // 发送缓冲区 uint8_t checksum = 0; // 校验和 uint8_t i; uint8_t j; // 1. 获取流量数据(根据你的实际数据源选择) uint32_t flow_data = flow_pulse_count; // 使用脉冲计数 // 或者: uint32_t flow_data = (uint32_t)(flow_rate_l_min * 100); // 使用流量值(放大100倍) // 2. 构建数据帧 tx_buffer[0] = 0x5A; // 帧头 tx_buffer[1] = 0x03; // 命令字(请求流量数据) tx_buffer[2] = 0x04; // 数据长度(4字节) // 将32位流量数据分解为4个字节(小端序) tx_buffer[3] = (flow_data >> 0) & 0xFF; // 最低字节 tx_buffer[4] = (flow_data >> 8) & 0xFF; tx_buffer[5] = (flow_data >> 16) & 0xFF; tx_buffer[6] = (flow_data >> 24) & 0xFF; // 最高字节 // 3. 计算校验和(从命令字到数据末尾) for( j = 1; j < 7; j++) { checksum ^= tx_buffer[j]; // 异或校验 } tx_buffer[7] = checksum; tx_buffer[8] = 0xA5; // 帧尾 // 4. 通过USART3发送数据 for( i = 0; i < 9; i++) { // 等待发送缓冲区为空 while(usart_flag_get(USART3, USART_TDBE_FLAG) == RESET) { // 可添加超时处理 } // 发送数据字节[6](@ref) usart_data_transmit(USART3, tx_buffer[i]); } // 5. 等待最后字节发送完成 // while(usart_flag_get(USART3, USART_FLAG_TC) == RESET) { // 确保所有数据都已物理发送完成 } /* add user code begin Header */ /** ************************************************************************** * @file at32a423_wk_config.c * @brief work bench config program ************************************************************************** * Copyright notice & Disclaimer * * The software Board Support Package (BSP) that is made available to * download from Artery official website is the copyrighted work of Artery. * Artery authorizes customers to use, copy, and distribute the BSP * software and its related documentation for the purpose of design and * development in conjunction with Artery microcontrollers. Use of the * software is governed by this copyright notice and the following disclaimer. * * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ************************************************************************** */ /* add user code end Header */ #include "at32a423_wk_config.h" //#define PULSES_PER_LITER 450 // 每升水对应的脉冲数 //volatile uint32_t pulse_count = 0; //float flow_rate_l_min = 0.0f; static __IO uint32_t fac_us; static __IO uint32_t fac_ms; #define STEP_DELAY_MS 50 gpio_init_type gpio_init_struct = {0}; crm_clocks_freq_type crm_clocks_freq_struct = {0}; /* private includes ----------------------------------------------------------*/ /* add user code begin private includes */ /* add user code end private includes */ /* private typedef -----------------------------------------------------------*/ /* add user code begin private typedef */ /* add user code end private typedef */ /* private define ------------------------------------------------------------*/ /* add user code begin private define */ /* add user code end private define */ /* private macro -------------------------------------------------------------*/ /* add user code begin private macro */ /* add user code end private macro */ /* private variables ---------------------------------------------------------*/ /* add user code begin private variables */ /* add user code end private variables */ /* private function prototypes --------------------------------------------*/ /* add user code begin function prototypes */ /* add user code end function prototypes */ /* private user code ---------------------------------------------------------*/ /* add user code begin 0 */ /* add user code end 0 */ /** * @brief system clock config program * @note the system clock is configured as follow: * system clock (sclk) = (hick / 6 * pll_ns)/(pll_ms * pll_fr) * system clock source = HICK_VALUE * - lick = on * - lext = off * - hick = on * - hext = off * - sclk = 150000000 * - ahbdiv = 1 * - ahbclk = 150000000 * - apb1div = 2 * - apb1clk = 75000000 * - apb2div = 1 * - apb2clk = 150000000 * - pll_ns = 75 * - pll_ms = 1 * - pll_fr = 2 * @param none * @retval none */ void wk_system_clock_config(void) { /* reset crm */ crm_reset(); /* config flash psr register */ flash_psr_set(FLASH_WAIT_CYCLE_4); /* enable pwc periph clock */ crm_periph_clock_enable(CRM_PWC_PERIPH_CLOCK, TRUE); /* config ldo voltage */ pwc_ldo_output_voltage_set(PWC_LDO_OUTPUT_1V3); /* enable lick */ crm_clock_source_enable(CRM_CLOCK_SOURCE_LICK, TRUE); /* wait till lick is ready */ while(crm_flag_get(CRM_LICK_STABLE_FLAG) != SET) { } /* enable hick */ crm_clock_source_enable(CRM_CLOCK_SOURCE_HICK, TRUE); /* wait till hick is ready */ while(crm_flag_get(CRM_HICK_STABLE_FLAG) != SET) { } /* config pll clock resource common frequency config list: pll source selected hick or hext(8mhz) _____________________________________________________________________________ | | | | | | | | | | sysclk | 150 | 144 | 120 | 108 | 96 | 72 | 36 | |________|_________|_________|_________|_________|_________|_________________| | | | | | | | | | |pll_ns | 75 | 72 | 120 | 108 | 96 | 72 | 72 | | | | | | | | | | |pll_ms | 1 | 1 | 1 | 1 | 1 | 1 | 1 | | | | | | | | | | |pll_fr | FR_2 | FR_2 | FR_4 | FR_4 | FR_4 | FR_4 | FR_8 | |________|_________|_________|_________|_________|_________|________|________| if pll clock source selects hext with other frequency values, or configure pll to other frequency values, please use the at32 new clock configuration tool for configuration. */ crm_pll_config(CRM_PLL_SOURCE_HICK, 75, 1, CRM_PLL_FR_2); /* enable pll */ crm_clock_source_enable(CRM_CLOCK_SOURCE_PLL, TRUE); /* wait till pll is ready */ while(crm_flag_get(CRM_PLL_STABLE_FLAG) != SET) { } /* config ahbclk */ crm_ahb_div_set(CRM_AHB_DIV_1); /* config apb2clk, the maximum frequency of APB2 clock is 150 MHz */ crm_apb2_div_set(CRM_APB2_DIV_1); /* config apb1clk, the maximum frequency of APB1 clock is 120 MHz */ crm_apb1_div_set(CRM_APB1_DIV_2); /* enable auto step mode */ crm_auto_step_mode_enable(TRUE); /* select pll as system clock source */ crm_sysclk_switch(CRM_SCLK_PLL); /* wait till pll is used as system clock source */ while(crm_sysclk_switch_status_get() != CRM_SCLK_PLL) { } /* disable auto step mode */ crm_auto_step_mode_enable(FALSE); /* update system_core_clock global variable */ system_core_clock_update(); } /** * @brief config periph clock * @param none * @retval none */ void wk_periph_clock_config(void) { /* enable gpioa periph clock */ crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); /* enable gpiob periph clock */ crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE); /* enable gpiof periph clock */ crm_periph_clock_enable(CRM_GPIOF_PERIPH_CLOCK, TRUE); /* enable tmr2 periph clock */ crm_periph_clock_enable(CRM_TMR2_PERIPH_CLOCK, TRUE); /* enable usart3 periph clock */ crm_periph_clock_enable(CRM_USART3_PERIPH_CLOCK, TRUE); /* enable usart1 periph clock */ crm_periph_clock_enable(CRM_USART1_PERIPH_CLOCK, TRUE); /* enable adc1 periph clock */ crm_periph_clock_enable(CRM_ADC1_PERIPH_CLOCK, TRUE); } /** * @brief nvic config * @param none * @retval none */ void wk_nvic_config(void) { nvic_priority_group_config(NVIC_PRIORITY_GROUP_4); NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 0)); nvic_irq_enable(ADC1_IRQn, 0, 0); } /** * @brief init usart1 function * @param none * @retval none */ void wk_usart1_init(void) { /* add user code begin usart1_init 0 */ /* add user code end usart1_init 0 */ gpio_init_type gpio_init_struct; gpio_default_para_init(&gpio_init_struct); /* add user code begin usart1_init 1 */ /* add user code end usart1_init 1 */ /* configure the TX pin */ gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_pins = GPIO_PINS_9; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init(GPIOA, &gpio_init_struct); gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE9, GPIO_MUX_7); /* configure the RX pin */ gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_pins = GPIO_PINS_10; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init(GPIOA, &gpio_init_struct); gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE10, GPIO_MUX_7); /* config usart1 clock source */ crm_usart_clock_select(CRM_USART1, CRM_USART_CLOCK_SOURCE_PCLK); /* configure param */ usart_init(USART1, 115200, USART_DATA_8BITS, USART_STOP_1_BIT); usart_transmitter_enable(USART1, TRUE); usart_receiver_enable(USART1, TRUE); usart_parity_selection_config(USART1, USART_PARITY_NONE); usart_hardware_flow_control_set(USART1, USART_HARDWARE_FLOW_NONE); usart_enable(USART1, TRUE); /* add user code begin usart1_init 2 */ /* add user code end usart1_init 2 */ } /** * @brief init usart3 function * @param none * @retval none */ void wk_usart3_init(void) { /* add user code begin usart3_init 0 */ /* add user code end usart3_init 0 */ gpio_init_type gpio_init_struct; gpio_default_para_init(&gpio_init_struct); /* add user code begin usart3_init 1 */ /* add user code end usart3_init 1 */ /* configure the TX pin */ gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_pins = GPIO_PINS_7; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init(GPIOA, &gpio_init_struct); gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE7, GPIO_MUX_7); /* configure the RX pin */ gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_pins = GPIO_PINS_5; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init(GPIOA, &gpio_init_struct); gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE5, GPIO_MUX_7); /* config usart3 clock source */ crm_usart_clock_select(CRM_USART3, CRM_USART_CLOCK_SOURCE_PCLK); /* configure param */ usart_init(USART3, 115200, USART_DATA_8BITS, USART_STOP_1_BIT); usart_transmitter_enable(USART3, TRUE); usart_receiver_enable(USART3, TRUE); usart_parity_selection_config(USART3, USART_PARITY_NONE); usart_hardware_flow_control_set(USART3, USART_HARDWARE_FLOW_NONE); usart_enable(USART3, TRUE); usart_interrupt_enable(USART3, USART_RDBF_INT, TRUE); nvic_irq_enable(USART3_IRQn, 0, 0); // 设置合适的中断优先级 usart_enable(USART3, TRUE); /* add user code begin usart3_init 2 */ /* add user code end usart3_init 2 */ } /** * @brief init adc1 function. * @param none * @retval none */ void wk_adc1_init(void) { /* add user code begin adc1_init 0 */ /* add user code end adc1_init 0 */ gpio_init_type gpio_init_struct; adc_common_config_type adc_common_struct; adc_base_config_type adc_base_struct; gpio_default_para_init(&gpio_init_struct); /* add user code begin adc1_init 1 */ /* add user code end adc1_init 1 */ /* configure the IN0 pin */ gpio_init_struct.gpio_mode = GPIO_MODE_ANALOG; gpio_init_struct.gpio_pins = GPIO_PINS_0; gpio_init(GPIOA, &gpio_init_struct); /* configure the IN1 pin */ gpio_init_struct.gpio_mode = GPIO_MODE_ANALOG; gpio_init_struct.gpio_pins = GPIO_PINS_1; gpio_init(GPIOA, &gpio_init_struct); /* configure the IN2 pin */ gpio_init_struct.gpio_mode = GPIO_MODE_ANALOG; gpio_init_struct.gpio_pins = GPIO_PINS_2; gpio_init(GPIOA, &gpio_init_struct); /* configure the IN3 pin */ gpio_init_struct.gpio_mode = GPIO_MODE_ANALOG; gpio_init_struct.gpio_pins = GPIO_PINS_3; gpio_init(GPIOA, &gpio_init_struct); /* configure the IN4 pin */ gpio_init_struct.gpio_mode = GPIO_MODE_ANALOG; gpio_init_struct.gpio_pins = GPIO_PINS_4; gpio_init(GPIOA, &gpio_init_struct); /* adc_common_settings--------------------------------------------------------------*/ /* config adc clock source */ crm_adc_clock_select(CRM_ADC_CLOCK_SOURCE_HCLK); adc_common_default_para_init(&adc_common_struct); /* config adc clock division */ adc_common_struct.div = ADC_HCLK_DIV_2; /* config inner temperature sensor and vintrv */ adc_common_struct.tempervintrv_state = FALSE; adc_common_config(&adc_common_struct); /* adc_settings------------------------------------------------------------------- */ adc_base_default_para_init(&adc_base_struct); adc_base_struct.sequence_mode = FALSE; adc_base_struct.repeat_mode = FALSE; adc_base_struct.data_align = ADC_RIGHT_ALIGNMENT; adc_base_struct.ordinary_channel_length = 1; adc_base_config(ADC1, &adc_base_struct); /* adc_ordinary_conversionmode---------------------------------------------------- */ adc_ordinary_channel_set(ADC1, ADC_CHANNEL_0, 1, ADC_SAMPLETIME_6_5); adc_ordinary_conversion_trigger_set(ADC1, ADC_ORDINARY_TRIG_SOFTWARE, ADC_ORDINARY_TRIG_EDGE_NONE); /** * Users need to configure ADC1 interrupt functions according to the actual application. * 1. Call the below function to enable the corresponding ADC1 interrupt. * --adc_interrupt_enable(...) * 2. Add the user's interrupt handler code into the below function in the at32a423_int.c file. * --void ADC1_IRQHandler(void) */ adc_enable(ADC1, TRUE); while(adc_flag_get(ADC1, ADC_RDY_FLAG) == RESET); /* adc calibration---------------------------------------------------------------- */ adc_calibration_init(ADC1); while(adc_calibration_init_status_get(ADC1)); adc_calibration_start(ADC1); while(adc_calibration_status_get(ADC1)); /* add user code begin adc1_init 2 */ /* add user code end adc1_init 2 */ } /** * @brief init tmr2 function. * @param none * @retval none */ void wk_tmr2_init(void) { /* add user code begin tmr2_init 0 */ /* add user code end tmr2_init 0 */ gpio_init_type gpio_init_struct; tmr_input_config_type tmr_ic_init_struct; gpio_default_para_init(&gpio_init_struct); crm_periph_clock_enable(CRM_GPIOF_PERIPH_CLOCK, TRUE); // GPIOA时钟 crm_periph_clock_enable(CRM_TMR2_PERIPH_CLOCK, TRUE); // TIM2时钟 // crm_periph_clock_enable(CRM_IOMUX_PERIPH_CLOCK, TRUE); // IO复用时钟 /* add user code begin tmr2_init 1 */ /* add user code end tmr2_init 1 */ /* configure the tmr2 CH1 pin */ gpio_init_struct.gpio_pins = GPIO_PINS_6; gpio_init_struct.gpio_mode = GPIO_MODE_INPUT; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_pull = GPIO_PULL_UP; gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init(GPIOF, &gpio_init_struct); gpio_pin_mux_config(GPIOF, GPIO_PINS_SOURCE6, GPIO_MUX_1); /* configure counter settings */ tmr_base_init(TMR2, 0xffff, 0); tmr_cnt_dir_set(TMR2, TMR_COUNT_UP); tmr_clock_source_div_set(TMR2, TMR_CLOCK_DIV1); tmr_period_buffer_enable(TMR2, FALSE); /* configure primary mode settings */ tmr_sub_sync_mode_set(TMR2, FALSE); tmr_primary_mode_select(TMR2, TMR_PRIMARY_SEL_RESET); /* configure pwm input with ch1 */ // 配置输入捕获 tmr_ic_init_struct.input_filter_value = 0x0f; tmr_ic_init_struct.input_channel_select = TMR_SELECT_CHANNEL_1; tmr_ic_init_struct.input_mapped_select = TMR_CC_CHANNEL_MAPPED_DIRECT; tmr_ic_init_struct.input_polarity_select = TMR_INPUT_RISING_EDGE; tmr_pwm_input_config(TMR2, &tmr_ic_init_struct, TMR_CHANNEL_INPUT_DIV_1); tmr_trigger_input_select(TMR2, TMR_SUB_INPUT_SEL_C1DF1); tmr_sub_mode_select(TMR2, TMR_SUB_RESET_MODE); nvic_priority_group_config(NVIC_PRIORITY_GROUP_4); // 启动计数器 nvic_irq_enable(TMR2_GLOBAL_IRQn, 1, 0); tmr_interrupt_enable(TMR2, TMR_C1_INT, TRUE); tmr_interrupt_enable(TMR2, TMR_OVF_INT, TRUE); // 启动计数器 tmr_counter_enable(TMR2, TRUE); /* add user code begin tmr2_init 2 */ /* add user code end tmr2_init 2 */ } void wk_tmr3_init(void) { /* add user code begin tmr3_init 0 */ /* add user code end tmr3_init 0 */ gpio_init_type gpio_init_struct; tmr_input_config_type tmr_input_struct; tmr_input_config_type tmr_ic_init_struct; gpio_default_para_init(&gpio_init_struct); /* add user code begin tmr3_init 1 */ /* add user code end tmr3_init 1 */ /* configure the tmr3 CH1 pin */ gpio_init_struct.gpio_pins = GPIO_PINS_6; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init(GPIOA, &gpio_init_struct); gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE6, GPIO_MUX_2); /* configure the tmr3 CH3 pin */ gpio_init_struct.gpio_pins = GPIO_PINS_0; gpio_init_struct.gpio_mode = GPIO_MODE_MUX; gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; gpio_init_struct.gpio_pull = GPIO_PULL_NONE; gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE; gpio_init(GPIOB, &gpio_init_struct); gpio_pin_mux_config(GPIOB, GPIO_PINS_SOURCE0, GPIO_MUX_2); /* configure counter settings */ tmr_base_init(TMR3, 65535, 0); tmr_cnt_dir_set(TMR3, TMR_COUNT_UP); tmr_clock_source_div_set(TMR3, TMR_CLOCK_DIV1); tmr_period_buffer_enable(TMR3, FALSE); /* configure primary mode settings */ tmr_sub_sync_mode_set(TMR3, FALSE); tmr_primary_mode_select(TMR3, TMR_PRIMARY_SEL_RESET); /* configure channel 3 input settings */ tmr_input_struct.input_channel_select = TMR_SELECT_CHANNEL_3; tmr_input_struct.input_mapped_select = TMR_CC_CHANNEL_MAPPED_DIRECT; tmr_input_struct.input_polarity_select = TMR_INPUT_RISING_EDGE; tmr_input_struct.input_filter_value = 0; tmr_input_channel_init(TMR3, &tmr_input_struct, TMR_CHANNEL_INPUT_DIV_1); /* configure pwm input with ch1 */ tmr_ic_init_struct.input_filter_value = 0; tmr_ic_init_struct.input_channel_select = TMR_SELECT_CHANNEL_1; tmr_ic_init_struct.input_mapped_select = TMR_CC_CHANNEL_MAPPED_DIRECT; tmr_ic_init_struct.input_polarity_select = TMR_INPUT_RISING_EDGE; tmr_pwm_input_config(TMR3, &tmr_ic_init_struct, TMR_CHANNEL_INPUT_DIV_1); tmr_trigger_input_select(TMR3, TMR_SUB_INPUT_SEL_C1DF1); tmr_sub_mode_select(TMR3, TMR_SUB_RESET_MODE); tmr_counter_enable(TMR3, TRUE); /* add user code begin tmr3_init 2 */ /* add user code end tmr3_init 2 */ } //void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { // if (htim->Instance == TIM2) { // pulse_count++; // 脉冲计数加1 // } //}void Calculate_FlowRate(void) { // static uint32_t last_pulse_count = 0; // uint32_t pulses_in_interval; // float time_interval_s = 1.0f; // 计算间隔1秒 // // pulses_in_interval = pulse_count - last_pulse_count; // last_pulse_count = pulse_count; // // // 流量计算公式:流量(L/min) = (脉冲数/脉冲每升) × (60/时间间隔秒) // flow_rate_l_min = (pulses_in_interval / (float)PULSES_PER_LITER) * (60.0f / time_interval_s); //} /* add user code begin 1 */ /* add user code end 1 */ void delay_init(void) { /* configure systick */ systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV); fac_us = system_core_clock / (1000000U); fac_ms = fac_us * (1000U); } void delay_us(uint32_t nus) { uint32_t temp = 0; SysTick->LOAD = (uint32_t)(nus * fac_us); SysTick->VAL = 0x00; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ; do { temp = SysTick->CTRL; }while((temp & 0x01) && !(temp & (1 << 16))); SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; SysTick->VAL = 0x00; } /** * @brief inserts a delay time. * @param nms: specifies the delay time length, in milliseconds. * @retval none */ void delay_ms(uint16_t nms) { uint32_t temp = 0; while(nms) { if(nms > STEP_DELAY_MS) { SysTick->LOAD = (uint32_t)(STEP_DELAY_MS * fac_ms); nms -= STEP_DELAY_MS; } else { SysTick->LOAD = (uint32_t)(nms * fac_ms); nms = 0; } SysTick->VAL = 0x00; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; do { temp = SysTick->CTRL; }while((temp & 0x01) && !(temp & (1 << 16))); SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; SysTick->VAL = 0x00; } } /** * @brief inserts a delay time. * @param sec: specifies the delay time, in seconds. * @retval none */ void delay_sec(uint16_t sec) { uint16_t index; for(index = 0; index < sec; index++) { delay_ms(500); delay_ms(500); } } 怎么过虑占空比40到60之外脉冲波形

#include "mytc1.h" #include "delay1.h" #include "gd32f303e_eval.h" #include "FreeRTOS.h" //FreeRTOS使用 #include "task.h" static u32 fac_us=0; //us延时倍乘数 static u16 fac_ms=0; //ms延时倍乘数,在os下,代表每个节拍的ms数 extern void xPortSysTickHandler( void ); /*! \brief configure systick \param[in] none \param[out] none \retval none */ void systick_config(void) { /* setup systick timer for 1000Hz interrupts */ SysTick_Config(SystemCoreClock / 1000U); /* configure the systick handler priority */ NVIC_SetPriority(SysTick_IRQn, 0x00U); fac_us=SystemCoreClock/120;//120M/120=1us fac_us=fac_us; fac_ms=1000/configTICK_RATE_HZ; //代表OS可以延时的最少单位 } void SysTick_Handler(void) { if(xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED)//系统已经运行 { xPortSysTickHandler(); } Timer0Handler1(); } //执行一次约37ns纳妙 void delay_nop(unsigned int dnop) { unsigned int i; for(i=0; i<dnop; i++)//37ns纳妙 ; } //延时us,不会引起任务调度 //peter chen拟定粗略延时函数,不采用定时器中断来做. void delay_xus(unsigned int dus) { unsigned int i; for(i=0; i<dus; i++) { delay_nop(27);//27*37ns=999us } } //延时us,采用定时器做法 void delay_us(uint32_t dus) { // u32 ticks; // u32 told,tnow,tcnt=0; // u32 reload=SysTick->LOAD; //LOAD的值 // // if(xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED)//系统已经运行 // { // ticks=dus*fac_us; //需要的节拍数 // told=SysTick->VAL; //刚进入时的计数器值 // while(1) // { // tnow=SysTick->VAL; // if(tnow!=told) // { // if(tnow<told)tcnt+=told-tnow; //这里注意一下SYSTICK是一个递减的计数器就可以了. // else tcnt+=reload-tnow+told; // told=tnow; // if(tcnt>=ticks)break; //时间超过/等于要延迟的时间,则退出. // } // }; // } // else delay_xus(dus); } //延时nms,会引起任务调度 //nms:要延时的ms数 //nms:0~65535 //void delay_ms(u32 nms) //{ // if(xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED)//系统已经运行 // vTaskDelay(nms); //FreeRTOS延时 //} void delay_ms(u32 nms) { //备注:假如fac_ms是10ms,则表示,若nms>10,就启用调度,不足10ms,就用delay_us //如果fac_ms是1,则nms%=fac_ms以后,就等于0;后面的delay_us也不执行 if(xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED)//系统已经运行 { if(nms>=fac_ms) //延时的时间大于OS的最少时间周期 { vTaskDelay(nms/fac_ms); //FreeRTOS延时 } nms%=fac_ms; //OS已经无法提供这么小的延时了,采用普通方式延时 } delay_us((u32)(nms*1000)); //普通方式延时 } //延时nms,不会引起任务调度 //nms:要延时的ms数 void delay_xms(u32 nms) { u32 i; for(i=0; i<nms; i++) delay_xus(1000); } //时间比较函数 //if(Tfabs( j, T10ms )>7) //if( Tfabs(ledt,Tsec )>1) clock_t Tfabs( clock_t tim0, clock_t tim1 ) //Tsec { if( tim1 >= tim0 ) { return ( tim1 - tim0 ); } else { return( tim0 - tim1 ); } } //========================================================== uint ledcnt=0; void ledm(uint md)//0闪,1开,2关 { uint CT=1000; if(md==0) { CT=1000; ledcnt++; if(ledcnt<CT) gd_eval_led_on(LED2); else if(ledcnt<CT*2) gd_eval_led_off(LED2); else ledcnt=0; } else if(md==3) { ledcnt++; CT=200; if(ledcnt<CT) gd_eval_led_on(LED2); else if(ledcnt<CT*2) gd_eval_led_off(LED2); else ledcnt=0; } else if(md==1) gd_eval_led_on(LED2); else if(md==2) gd_eval_led_off(LED2); } 代码解析

#include <stdio.h> #include <stdint.h> #include "main.h" #include "PhyAll.h" #include "FunAll.h" volatile unsigned long ulSysTickCnt; unsigned long ulSysTimeMax; unsigned long ulLastVal; #define SYS_TIME_100US 14400 //144*100 #define SYS_TIME_500US 72000 //144*500 static unsigned char ucTimer1,ucTimer3; //ucTimer2, unsigned short usTimer4; static unsigned long ulSysTickIRQOffCnt=0; static void SystemTickInit(void); /** * @brief Main program. */ int main(void) { // unsigned short i; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); //NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x5000); SystemTickInit(); /* Configure the system clock */ __enable_irq(); /*if(FLASH_GetReadOutProtectionSTS()==RESET){ //»¹Ã»¿ªÆô¶Á±£»¤Ôò¿ªÆô // FLASH_ClockInit(); FLASH_Unlock(); FLASH_ReadOutProtectionL1(ENABLE); //¿ªÆôL1¼¶¶Á±£»¤ FLASH_Lock(); }*/ /* Initialize all configured peripherals */ PhyGpio_Init(); Phy_CanInit(); FunData_ParaInit(); ObjCan1_Init(); ObjCan2_Init(); ExtCan_ParaInit(); PhyIWDG_Init(IWDG_PRESCALER_DIV4,3000); //´ó¸Å160MSÒç³ö while(1) { if(Sys_Time0MS1Check()==TRUE) { //0.1msÖ´Ðеĺ¯Êý ObjCan1_RxDeal(); ObjCan2_RxDeal(); ucTimer1++; if(ucTimer1>=20)//2msÖ´ÐÐ { ucTimer1 = 0; PhyGpio_ReadInput(); PhyGpio_WriteOutput(); ObjCan1_Main(); ObjCan2_Main(); FunData_DoDeal(); FunData_LedDeal(); FunData_EidDeal(); } ucTimer3++; if(ucTimer3>=100) //10ms { ucTimer3 = 0; PhyIWDG_Feed(); } } } } static void SystemTickInit(void) { ulSysTimeMax = SystemCoreClock / 1000U; //tickÖжÏÖÜÆÚ1ms SysTick->LOAD = (uint32_t) (ulSysTimeMax - 1UL); /* set reload register */ NVIC_SetPriority(SysTick_IRQn, 0); SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | //ʹÓÃϵͳʱÖÓHCLK SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ } BOOL Sys_Time0MS5Check(void) { unsigned long ulSysTime; unsigned long ulDeltaTime; ulSysTime = SysTick->VAL; if (ulSysTime <= ulLastVal) { ulDeltaTime = ulLastVal - ulSysTime; } else { ulDeltaTime = ulLastVal + ulSysTimeMax - ulSysTime; } if (ulDeltaTime >= SYS_TIME_500US) { if (ulLastVal >= SYS_TIME_500US) { ulLastVal -= SYS_TIME_500US; } else { ulLastVal = ulLastVal + ulSysTimeMax - SYS_TIME_500US; } return TRUE; } return FALSE; } BOOL Sys_Time0MS1Check(void) { unsigned long ulSysTime; unsigned long ulDeltaTime; ulSysTime = SysTick->VAL; if (ulSysTime <= ulLastVal) { ulDeltaTime = ulLastVal - ulSysTime; } else { ulDeltaTime = ulLastVal + ulSysTimeMax - ulSysTime; } if (ulDeltaTime >= SYS_TIME_100US) { if (ulLastVal >= SYS_TIME_100US) { ulLastVal -= SYS_TIME_100US; } else { ulLastVal = ulLastVal + ulSysTimeMax - SYS_TIME_100US; } return TRUE; } return FALSE; } void HAL_SuspendTick(void) { ulSysTickIRQOffCnt++; /* Disable SysTick Interrupt */ CLEAR_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); } void HAL_ResumeTick(void) { if(ulSysTickIRQOffCnt) { ulSysTickIRQOffCnt--; } if(0==ulSysTickIRQOffCnt) { /* Enable SysTick Interrupt */ SET_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); } }

/** ****************************************************************************** * @file system_stm32f10x.c * @author MCD Application Team * @version V3.5.1 * @date 08-September-2021 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File. * * 1. This file provides two functions and one global variable to be called from * user application: * - SystemInit(): Setups the system clock (System clock source, PLL Multiplier * factors, AHB/APBx prescalers and Flash settings). * This function is called at startup just after reset and * before branch to main program. This call is made inside * the "startup_stm32f10x_xx.s" file. * * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used * by the user application to setup the SysTick * timer or configure other parameters. * * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must * be called whenever the core clock is changed * during program execution. * * 2. After each device reset the HSI (8 MHz) is used as system clock source. * Then SystemInit() function is called, in "startup_stm32f10x_xx.s" file, to * configure the system clock before to branch to main program. * * 3. If the system clock source selected by user fails to startup, the SystemInit() * function will do nothing and HSI still used as system clock source. User can * add some code to deal with this issue inside the SetSysClock() function. * * 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depending on * the product used), refer to "HSE_VALUE" define in "stm32f10x.h" file. * When HSE is used as system clock source, directly or through PLL, and you * are using different crystal you have to adapt the HSE value to your own * configuration. * ****************************************************************************** * @attention * * Copyright (c) 2011 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f10x_system * @{ */ /** @addtogroup STM32F10x_System_Private_Includes * @{ */ #include "stm32f10x.h" /** * @} */ /** @addtogroup STM32F10x_System_Private_TypesDefinitions * @{ */ /** * @} */ /** @addtogroup STM32F10x_System_Private_Defines * @{ */ /*!< Uncomment the line corresponding to the desired System clock (SYSCLK) frequency (after reset the HSI is used as SYSCLK source) IMPORTANT NOTE: ============== 1. After each device reset the HSI is used as System clock source. 2. Please make sure that the selected System clock doesn't exceed your device's maximum frequency. 3. If none of the define below is enabled, the HSI is used as System clock source. 4. The System clock configuration functions provided within this file assume that: - For Low, Medium and High density Value line devices an external 8MHz crystal is used to drive the System clock. - For Low, Medium and High density devices an external 8MHz crystal is used to drive the System clock. - For Connectivity line devices an external 25MHz crystal is used to drive the System clock. If you are using different crystal you have to adapt those functions accordingly. */ #if defined (STM32F10X_LD_VL) || (defined STM32F10X_MD_VL) || (defined STM32F10X_HD_VL) /* #define SYSCLK_FREQ_HSE HSE_VALUE */ #define SYSCLK_FREQ_24MHz 24000000 #else /* #define SYSCLK_FREQ_HSE HSE_VALUE */ /* #define SYSCLK_FREQ_24MHz 24000000 */ /* #define SYSCLK_FREQ_36MHz 36000000 */ /* #define SYSCLK_FREQ_48MHz 48000000 */ /* #define SYSCLK_FREQ_56MHz 56000000 */ #define SYSCLK_FREQ_72MHz 72000000 #endif /*!< Uncomment the following line if you need to use external SRAM mounted on STM3210E-EVAL board (STM32 High density and XL-density devices) or on STM32100E-EVAL board (STM32 High-density value line devices) as data memory */ #if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL) /* #define DATA_IN_ExtSRAM */ #endif /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ #define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ /** * @} */ /** @addtogroup STM32F10x_System_Private_Macros * @{ */ /** * @} */ /** @addtogroup STM32F10x_System_Private_Variables * @{ */ /******************************************************************************* * Clock Definitions *******************************************************************************/ #ifdef SYSCLK_FREQ_HSE uint32_t SystemCoreClock = SYSCLK_FREQ_HSE; /*!< System Clock Frequency (Core Clock) */ #elif defined SYSCLK_FREQ_24MHz uint32_t SystemCoreClock = SYSCLK_FREQ_24MHz; /*!< System Clock Frequency (Core Clock) */ #elif defined SYSCLK_FREQ_36MHz uint32_t SystemCoreClock = SYSCLK_FREQ_36MHz; /*!< System Clock Frequency (Core Clock) */ #elif defined SYSCLK_FREQ_48MHz uint32_t SystemCoreClock = SYSCLK_FREQ_48MHz; /*!< System Clock Frequency (Core Clock) */ #elif defined SYSCLK_FREQ_56MHz uint32_t SystemCoreClock = SYSCLK_FREQ_56MHz; /*!< System Clock Frequency (Core Clock) */ #elif defined SYSCLK_FREQ_72MHz uint32_t SystemCoreClock = SYSCLK_FREQ_72MHz; /*!< System Clock Frequency (Core Clock) */ #else /*!< HSI Selected as System Clock source */ uint32_t SystemCoreClock = HSI_VALUE; /*!< System Clock Frequency (Core Clock) */ #endif __I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /** * @} */ /** @addtogroup STM32F10x_System_Private_FunctionPrototypes * @{ */ static void SetSysClock(void); #ifdef SYSCLK_FREQ_HSE static void SetSysClockToHSE(void); #elif defined SYSCLK_FREQ_24MHz static void SetSysClockTo24(void); #elif defined SYSCLK_FREQ_36MHz static void SetSysClockTo36(void); #elif defined SYSCLK_FREQ_48MHz static void SetSysClockTo48(void); #elif defined SYSCLK_FREQ_56MHz static void SetSysClockTo56(void); #elif defined SYSCLK_FREQ_72MHz static void SetSysClockTo72(void); #endif #ifdef DATA_IN_ExtSRAM static void SystemInit_ExtMemCtl(void); #endif /* DATA_IN_ExtSRAM */ /** * @} */ /** @addtogroup STM32F10x_System_Private_Functions * @{ */ /** * @brief Setup the microcontroller system * Initialize the Embedded Flash Interface, the PLL and update the * SystemCoreClock variable. * @note This function should be used only after reset. * @param None * @retval None */ void SystemInit (void) { /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ /* Set HSION bit */ RCC->CR |= (uint32_t)0x00000001; /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ #ifndef STM32F10X_CL RCC->CFGR &= (uint32_t)0xF8FF0000; #else RCC->CFGR &= (uint32_t)0xF0FF0000; #endif /* STM32F10X_CL */ /* Reset HSEON, CSSON and PLLON bits */ RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset HSEBYP bit */ RCC->CR &= (uint32_t)0xFFFBFFFF; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ RCC->CFGR &= (uint32_t)0xFF80FFFF; #ifdef STM32F10X_CL /* Reset PLL2ON and PLL3ON bits */ RCC->CR &= (uint32_t)0xEBFFFFFF; /* Disable all interrupts and clear pending bits */ RCC->CIR = 0x00FF0000; /* Reset CFGR2 register */ RCC->CFGR2 = 0x00000000; #elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL) /* Disable all interrupts and clear pending bits */ RCC->CIR = 0x009F0000; /* Reset CFGR2 register */ RCC->CFGR2 = 0x00000000; #else /* Disable all interrupts and clear pending bits */ RCC->CIR = 0x009F0000; #endif /* STM32F10X_CL */ #if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL) #ifdef DATA_IN_ExtSRAM SystemInit_ExtMemCtl(); #endif /* DATA_IN_ExtSRAM */ #endif /* Configure the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers */ /* Configure the Flash Latency cycles and enable prefetch buffer */ SetSysClock(); #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */ #else SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ #endif } /** * @brief Update SystemCoreClock variable according to Clock Register Values. * The SystemCoreClock variable contains the core clock (HCLK), it can * be used by the user application to setup the SysTick timer or configure * other parameters. * * @note Each time the core clock (HCLK) changes, this function must be called * to update SystemCoreClock variable value. Otherwise, any configuration * based on this variable will be incorrect. * * @note - The system frequency computed by this function is not the real * frequency in the chip. It is calculated based on the predefined * constant and the selected clock source: * * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) * * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) * * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) * or HSI_VALUE(*) multiplied by the PLL factors. * * (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value * 8 MHz) but the real value may vary depending on the variations * in voltage and temperature. * * (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value * 8 MHz or 25 MHz, depending on the product used), user has to ensure * that HSE_VALUE is same as the real frequency of the crystal used. * Otherwise, this function may have wrong result. * * - The result of this function could be not correct when using fractional * value for HSE crystal. * @param None * @retval None */ void SystemCoreClockUpdate (void) { uint32_t tmp = 0, pllmull = 0, pllsource = 0; #ifdef STM32F10X_CL uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0; #endif /* STM32F10X_CL */ #if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL) uint32_t prediv1factor = 0; #endif /* STM32F10X_LD_VL or STM32F10X_MD_VL or STM32F10X_HD_VL */ /* Get SYSCLK source -------------------------------------------------------*/ tmp = RCC->CFGR & RCC_CFGR_SWS; switch (tmp) { case 0x00: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; case 0x04: /* HSE used as system clock */ SystemCoreClock = HSE_VALUE; break; case 0x08: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ----------------------*/ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; #ifndef STM32F10X_CL pllmull = ( pllmull >> 18) + 2; if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { #if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL) prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; #else /* HSE selected as PLL clock entry */ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) {/* HSE oscillator clock divided by 2 */ SystemCoreClock = (HSE_VALUE >> 1) * pllmull; } else { SystemCoreClock = HSE_VALUE * pllmull; } #endif } #else pllmull = pllmull >> 18; if (pllmull != 0x0D) { pllmull += 2; } else { /* PLL multiplication factor = PLL input clock * 6.5 */ pllmull = 13 / 2; } if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else {/* PREDIV1 selected as PLL clock entry */ /* Get PREDIV1 clock source and division factor */ prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC; prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; if (prediv1source == 0) { /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; } else {/* PLL2 clock selected as PREDIV1 clock entry */ /* Get PREDIV2 division factor and PLL2 multiplication factor */ prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1; pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2; SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull; } } #endif /* STM32F10X_CL */ break; default: SystemCoreClock = HSI_VALUE; break; } /* Compute HCLK clock frequency ----------------*/ /* Get HCLK prescaler */ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } /** * @brief Configures the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers. * @param None * @retval None */ static void SetSysClock(void) { #ifdef SYSCLK_FREQ_HSE SetSysClockToHSE(); #elif defined SYSCLK_FREQ_24MHz SetSysClockTo24(); #elif defined SYSCLK_FREQ_36MHz SetSysClockTo36(); #elif defined SYSCLK_FREQ_48MHz SetSysClockTo48(); #elif defined SYSCLK_FREQ_56MHz SetSysClockTo56(); #elif defined SYSCLK_FREQ_72MHz SetSysClockTo72(); #endif /* If none of the define above is enabled, the HSI is used as System clock source (default after reset) */ } /** * @brief Setup the external memory controller. Called in startup_stm32f10x.s * before jump to __main * @param None * @retval None */ #ifdef DATA_IN_ExtSRAM /** * @brief Setup the external memory controller. * Called in startup_stm32f10x_xx.s/.c before jump to main. * This function configures the external SRAM mounted on STM3210E-EVAL * board (STM32 High density devices). This SRAM will be used as program * data memory (including heap and stack). * @param None * @retval None */ void SystemInit_ExtMemCtl(void) { /*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is required, then adjust the Register Addresses */ /* Enable FSMC clock */ RCC->AHBENR = 0x00000114; /* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */ RCC->APB2ENR = 0x000001E0; /* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/ /*---------------- SRAM Address lines configuration -------------------------*/ /*---------------- NOE and NWE configuration --------------------------------*/ /*---------------- NE3 configuration ----------------------------------------*/ /*---------------- NBL0, NBL1 configuration ---------------------------------*/ GPIOD->CRL = 0x44BB44BB; GPIOD->CRH = 0xBBBBBBBB; GPIOE->CRL = 0xB44444BB; GPIOE->CRH = 0xBBBBBBBB; GPIOF->CRL = 0x44BBBBBB; GPIOF->CRH = 0xBBBB4444; GPIOG->CRL = 0x44BBBBBB; GPIOG->CRH = 0x44444B44; /*---------------- FSMC Configuration ---------------------------------------*/ /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/ FSMC_Bank1->BTCR[4] = 0x00001011; FSMC_Bank1->BTCR[5] = 0x00000200; } #endif /* DATA_IN_ExtSRAM */ #ifdef SYSCLK_FREQ_HSE /** * @brief Selects HSE as System clock source and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockToHSE(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { #if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 0 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); #ifndef STM32F10X_CL FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0; #else if (HSE_VALUE <= 24000000) { FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0; } else { FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1; } #endif /* STM32F10X_CL */ #endif /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1; /* Select HSE as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_HSE; /* Wait till HSE is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x04) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #elif defined SYSCLK_FREQ_24MHz /** * @brief Sets System clock frequency to 24MHz and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockTo24(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { #if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 0 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0; #endif /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1; #ifdef STM32F10X_CL /* Configure PLLs ------------------------------------------------------*/ /* PLL configuration: PLLCLK = PREDIV1 * 6 = 24 MHz */ RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLMULL6); /* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ /* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */ RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL | RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC); RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 | RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10); /* Enable PLL2 */ RCC->CR |= RCC_CR_PLL2ON; /* Wait till PLL2 is ready */ while((RCC->CR & RCC_CR_PLL2RDY) == 0) { } #elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL) /* PLL configuration: = (HSE / 2) * 6 = 24 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLXTPRE_PREDIV1_Div2 | RCC_CFGR_PLLMULL6); #else /* PLL configuration: = (HSE / 2) * 6 = 24 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL6); #endif /* STM32F10X_CL */ /* Enable PLL */ RCC->CR |= RCC_CR_PLLON; /* Wait till PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #elif defined SYSCLK_FREQ_36MHz /** * @brief Sets System clock frequency to 36MHz and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockTo36(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 1 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1; /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1; #ifdef STM32F10X_CL /* Configure PLLs ------------------------------------------------------*/ /* PLL configuration: PLLCLK = PREDIV1 * 9 = 36 MHz */ RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLMULL9); /*!< PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ /* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */ RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL | RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC); RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 | RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10); /* Enable PLL2 */ RCC->CR |= RCC_CR_PLL2ON; /* Wait till PLL2 is ready */ while((RCC->CR & RCC_CR_PLL2RDY) == 0) { } #else /* PLL configuration: PLLCLK = (HSE / 2) * 9 = 36 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL9); #endif /* STM32F10X_CL */ /* Enable PLL */ RCC->CR |= RCC_CR_PLLON; /* Wait till PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #elif defined SYSCLK_FREQ_48MHz /** * @brief Sets System clock frequency to 48MHz and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockTo48(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 1 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1; /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2; #ifdef STM32F10X_CL /* Configure PLLs ------------------------------------------------------*/ /* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ /* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */ RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL | RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC); RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 | RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5); /* Enable PLL2 */ RCC->CR |= RCC_CR_PLL2ON; /* Wait till PLL2 is ready */ while((RCC->CR & RCC_CR_PLL2RDY) == 0) { } /* PLL configuration: PLLCLK = PREDIV1 * 6 = 48 MHz */ RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLMULL6); #else /* PLL configuration: PLLCLK = HSE * 6 = 48 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL6); #endif /* STM32F10X_CL */ /* Enable PLL */ RCC->CR |= RCC_CR_PLLON; /* Wait till PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #elif defined SYSCLK_FREQ_56MHz /** * @brief Sets System clock frequency to 56MHz and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockTo56(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 2 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2; /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2; #ifdef STM32F10X_CL /* Configure PLLs ------------------------------------------------------*/ /* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ /* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */ RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL | RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC); RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 | RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5); /* Enable PLL2 */ RCC->CR |= RCC_CR_PLL2ON; /* Wait till PLL2 is ready */ while((RCC->CR & RCC_CR_PLL2RDY) == 0) { } /* PLL configuration: PLLCLK = PREDIV1 * 7 = 56 MHz */ RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLMULL7); #else /* PLL configuration: PLLCLK = HSE * 7 = 56 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL7); #endif /* STM32F10X_CL */ /* Enable PLL */ RCC->CR |= RCC_CR_PLLON; /* Wait till PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #elif defined SYSCLK_FREQ_72MHz /** * @brief Sets System clock frequency to 72MHz and configure HCLK, PCLK2 * and PCLK1 prescalers. * @note This function should be used only after reset. * @param None * @retval None */ static void SetSysClockTo72(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/ /* Enable HSE */ RCC->CR |= ((uint32_t)RCC_CR_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { /* Enable Prefetch Buffer */ FLASH->ACR |= FLASH_ACR_PRFTBE; /* Flash 2 wait state */ FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2; /* HCLK = SYSCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2; #ifdef STM32F10X_CL /* Configure PLLs ------------------------------------------------------*/ /* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ /* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */ RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL | RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC); RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 | RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5); /* Enable PLL2 */ RCC->CR |= RCC_CR_PLL2ON; /* Wait till PLL2 is ready */ while((RCC->CR & RCC_CR_PLL2RDY) == 0) { } /* PLL configuration: PLLCLK = PREDIV1 * 9 = 72 MHz */ RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLMULL9); #else /* PLL configuration: PLLCLK = HSE * 9 = 72 MHz */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL9); #endif /* STM32F10X_CL */ /* Enable PLL */ RCC->CR |= RCC_CR_PLLON; /* Wait till PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ } } #endif /** * @} */ /** * @} */ /** * @} */ source\main.c(49): warning: #177-D: variable "buffer" was declared but never referenced char buffer[32]; source\main.c: 1 warning, 0 errors compiling system_stm32f10x.c... RTE\Device\STM32F103C8\system_stm32f10x.c(266): error: #20: identifier "FLASH_BASE" is undefined SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ RTE\Device\STM32F103C8\system_stm32f10x.c(323): error: #20: identifier "HSI_VALUE" is undefined SystemCoreClock = HSI_VALUE; RTE\Device\STM32F103C8\system_stm32f10x.c(326): error: #20: identifier "HSE_VALUE" is undefined SystemCoreClock = HSE_VALUE; RTE\Device\STM32F103C8\system_stm32f10x.c(999): error: #20: identifier "HSE_STARTUP_TIMEOUT" is undefined } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); RTE\Device\STM32F103C8\system_stm32f10x.c: 0 warnings, 4 errors ".\Obj\ADC.axf" - 4 Error(s), 1 Warning(s). Target not created. Build Time Elapsed: 00:00:01

void TIM3_init(uint32_t Period,uint32_t Prescaler) { __HAL_RCC_TIM3_CLK_ENABLE(); TIM_HandleTypeDef TimHandle; TimHandle.Instance = TIM3; /* Select TIM3 */ TimHandle.Init.Period = Period - 1; /* Auto-reload value */ TimHandle.Init.Prescaler = Prescaler - 1; /* Prescaler is set to 1000-1 */ TimHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; /* No clock division */ TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; /* Up counting mode */ TimHandle.Init.RepetitionCounter = 1 - 1; /* No repetition counter */ TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; /* Auto-reload register not buffered */ HAL_NVIC_SetPriority(TIM3_IRQn, 2, 2); HAL_NVIC_EnableIRQ(TIM3_IRQn); /* TIM3 initialization */ if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK) { APP_ErrorHandler(); } /* Start TIM3 and enable interrupts */ if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK) { APP_ErrorHandler(); } } #ifndef __TIM_H #define __TIM_H #include "py32f0xx_hal.h" #include "main.h" void TIM3_init(uint32_t Period,uint32_t Prescaler); extern TIM_HandleTypeDef TimHandle;/** ****************************************************************************** * @file main.c * @author MCU Application Team * @brief Main program body ****************************************************************************** * @attention * *
© Copyright (c) 2023 Puya Semiconductor Co. * All rights reserved.
* * This software component is licensed by Puya under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** * @attention * *
© Copyright (c) 2016 STMicroelectronics. * All rights reserved.
* * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "Dr_Driver\bsp.h" #include "TIM\tim.h" #include "KEY\key.h" #include "MIC\mic.h" //TIM_HandleTypeDef TimHandle; static void APP_SystemClockConfig(void); uint8_t key_num; /** * @brief Main program. * @retval int */ int main(void) { /* Reset of all peripherals, Initializes the Systick */ HAL_Init(); //HAL_Delay(1000); uint8_t MIC_status=0; //mic状态 uint32_t smoking_tim=0;//吸烟时间 /* Configure the system clock */ APP_SystemClockConfig(); iwdg_init(); Dr_system_init(); //uart Dr_Uart_Debug_Printf("SystemCoreClock = %d\n\r",SystemCoreClock); TIM3_init(32000,1000);//100ms adc_Config(); KEY_init(); MIC_init(); #if (DEBUG_PRINTF == 1) Dr_Uart_Debug_Printf("SystemCoreClock = %d\n\r",SystemCoreClock); #endif while (1) { MIC_status= HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4); switch(key_num) { case 1:smoking_tim=300;break; case 2:smoking_tim=200;break; case 3:smoking_tim=100;break; default:break; } if(timer_1s_flag) { Dr_Uart_Debug_Printf("vbat = %d\r\n",(4095 * 1200) / g_get_adc[2]); //原电池电压 Dr_Uart_Debug_Printf("outvbat = %d\r\n",(g_get_adc[0]* 1200)/g_get_adc[2]); //待测电池电压 Dr_Uart_Debug_Printf("output = %d\r\n",(g_get_adc[1]* 1200)/g_get_adc[2]); //输出电压 Dr_Uart_Debug_Printf("smokingtim = %d\r\n",smoking_tim); //输出电压 Dr_Uart_Debug_Printf("MIC_status = %d\r\n",MIC_status); //输出电压 Dr_Uart_Debug_Printf("\r\n"); //输出电压 } if(timer_10ms_flag ) { adc_get(); timer_10ms_flag = 0; } if(timer_100ms_flag ) { timer_100ms_flag = 0; if(MIC_status) smoking_tim++; } if(timer_1s_flag) { timer_1s_flag=0; } fwdt_feed(); } } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { //BSP_LED_Toggle(LED_GREEN); //BSP_LED_On(LED_GREEN); smoking_tim=500; } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { static uint32_t last_time[3] = {0}; uint32_t current_time = HAL_GetTick(); Dr_Uart_Debug_Printf("KEY0 Pressed!\n"); // 判断是哪个按键触发的中断 if (GPIO_Pin == GPIO_PIN_5) { // KEY0 if (current_time - last_time[0] > 20) { // 消抖处理(20ms) last_time[0] = current_time; // 处理KEY0按下事件 Dr_Uart_Debug_Printf("KEY0 Pressed!\n"); } } else if (GPIO_Pin == GPIO_PIN_6) { // KEY1 if (current_time - last_time[1] > 20) { last_time[1] = current_time; // 处理KEY1按下事件 Dr_Uart_Debug_Printf("KEY1 Pressed!\n"); } } else if (GPIO_Pin == GPIO_PIN_7) { // KEY2 if (current_time - last_time[2] > 20) { last_time[2] = current_time; // 处理KEY2按下事件 Dr_Uart_Debug_Printf("KEY2 Pressed!\n"); } } } /** * @brief System Clock Configuration * @param None * @retval None */ static void APP_SystemClockConfig(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /* Oscillator Configuration */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; /* Select oscillators HSE, HSI, LSI, LSE */ RCC_OscInitStruct.HSIState = RCC_HSI_ON; /* Enable HSI */ RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; /* HSI not divided */ RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_24MHz; /* Configure HSI clock as 8MHz */ RCC_OscInitStruct.HSEState = RCC_HSE_OFF; /* Disable HSE */ // RCC_OscInitStruct.HSEFreq = RCC_HSE_16_32MHz; RCC_OscInitStruct.LSIState = RCC_LSI_OFF; /* Disable LSI */ RCC_OscInitStruct.LSEState = RCC_LSE_OFF; /* Disable LSE */ /*RCC_OscInitStruct.LSEDriver = RCC_LSEDRIVE_MEDIUM;*/ RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; /* Disable PLL */ RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; /* Configure oscillators */ if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { APP_ErrorHandler(); } /* Clock source configuration */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; /* Select clock types HCLK, SYSCLK, PCLK1 */ RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; /* Select HSI as the system clock */ RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; /* AHB clock not divide */ RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; /* APB clock not divided */ /* Configure clock source */ if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { APP_ErrorHandler(); } } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ void APP_ErrorHandler(void) { /* Infinite loop */ while (1) { } } /************************ (C) COPYRIGHT Puya *****END OF FILE******************/为什么只打印了一行SystemCoreClock = 48000000

volatile uint32_t step_count = 0; uint32_t target_steps = 0; // 目标步数 //// 设置步进电机速度(频率) //void set_stepper_speed(uint32_t frequency) //{ // // 计算ARR值:ARR = (定时器时钟 / (预分频系数 * 频率)) - 1 // uint32_t timer_clock = HAL_RCC_GetPCLK1Freq() * 2; // TIM2挂载在APB1 // uint32_t arr_val = (timer_clock / (htim2.Init.Prescaler * frequency)) - 1; // __HAL_TIM_SET_AUTORELOAD(&htim2, arr_val); // 设置周期[^3] // __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, arr_val / 2); // 50%占空比[^5] //} void move_stepper(uint32_t steps) { target_steps = steps; step_count = 0; // set_stepper_speed(speed); // 设置速度 HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1); // 启动PWM+中断 } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_TIM2_Init(); /* USER CODE BEGIN 2 */ HAL_GPIO_WritePin(GPIOA,GPIO_PIN_1,GPIO_PIN_SET); move_stepper(100); // HAL_GPIO_WritePin(GPIOA,GPIO_PIN_1,GPIO_PIN_SET); // HAL_TIM_PWM_Start_IT(&htim2,TIM_CHANNEL_1); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { // HAL_Delay(5000); // HAL_GPIO_WritePin(GPIOA,GPIO_PIN_1,GPIO_PIN_RESET); // move_stepper(500); // HAL_Delay(5000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == TIM2) { step_count++; if (step_count >= target_steps) { HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1); // 停止脉冲 } } }为什么该程序运行时,电机一直转,无法实现到指定步数停止?

void KEY_init(void) { __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = KEY_GPIO_PIN; GPIO_InitStruct.Mode = GPIO_MODE_EVT_FALLING; /* Push-pull output */ GPIO_InitStruct.Pull = GPIO_PULLUP; /* Enable pull-up */ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; /* GPIO speed */ HAL_GPIO_Init(KEY_GPIO_PORT, &GPIO_InitStruct); HAL_NVIC_SetPriority(EXTI4_15_IRQn, 0, 0); // EXTI4-15中断通道 HAL_NVIC_EnableIRQ(EXTI4_15_IRQn); }/** ****************************************************************************** * @file main.c * @author MCU Application Team * @brief Main program body ****************************************************************************** * @attention * *
© Copyright (c) 2023 Puya Semiconductor Co. * All rights reserved.
* * This software component is licensed by Puya under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** * @attention * *
© Copyright (c) 2016 STMicroelectronics. * All rights reserved.
* * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "Dr_Driver\bsp.h" #include "TIM\tim.h" #include "KEY\key.h" #include "MIC\mic.h" static void APP_SystemClockConfig(void); uint8_t key_num; /** * @brief Main program. * @retval int */ int main(void) { /* Reset of all peripherals, Initializes the Systick */ HAL_Init(); //HAL_Delay(1000); // uint8_t MIC_status=0; //mic状态 // uint32_t smoking_tim=0;//吸烟时间 /* Configure the system clock */ APP_SystemClockConfig(); iwdg_init(); Dr_system_init(); //uart Dr_Uart_Debug_Printf("SystemCoreClock = %d\n\r",SystemCoreClock); TIM3_init(32000,1000);//100ms adc_Config(); KEY_init(); MIC_init(); #if (DEBUG_PRINTF == 1) Dr_Uart_Debug_Printf("SystemCoreClock = %d\n\r",SystemCoreClock); #endif while (1) { MIC_status= HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4); switch(key_num) { case 1:smoking_tim=300;break; case 2:smoking_tim=200;break; case 3:smoking_tim=100;break; default:break; } if(timer_1s_flag) { Dr_Uart_Debug_Printf("vbat = %d\r\n",(4095 * 1200) / g_get_adc[2]); //原电池电压 Dr_Uart_Debug_Printf("outvbat = %d\r\n",(g_get_adc[0]* 1200)/g_get_adc[2]); //待测电池电压 Dr_Uart_Debug_Printf("output = %d\r\n",(g_get_adc[1]* 1200)/g_get_adc[2]); //输出电压 Dr_Uart_Debug_Printf("smokingtim = %d\r\n",smoking_tim); //输出电压 Dr_Uart_Debug_Printf("MIC_status = %d\r\n",MIC_status); //输出电压 Dr_Uart_Debug_Printf("\r\n"); //输出电压 } if(timer_10ms_flag ) { adc_get(); timer_10ms_flag = 0; } if(timer_100ms_flag ) { timer_100ms_flag = 0; if(MIC_status) smoking_tim++; } if(timer_1s_flag) { timer_1s_flag=0; } fwdt_feed(); } } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { //BSP_LED_Toggle(LED_GREEN); //BSP_LED_On(LED_GREEN); // smoking_tim=500; smoking_tim++; } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { } /** * @brief System Clock Configuration * @param None * @retval None */ static void APP_SystemClockConfig(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /* Oscillator Configuration */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; /* Select oscillators HSE, HSI, LSI, LSE */ RCC_OscInitStruct.HSIState = RCC_HSI_ON; /* Enable HSI */ RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; /* HSI not divided */ RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_24MHz; /* Configure HSI clock as 8MHz */ RCC_OscInitStruct.HSEState = RCC_HSE_OFF; /* Disable HSE */ // RCC_OscInitStruct.HSEFreq = RCC_HSE_16_32MHz; RCC_OscInitStruct.LSIState = RCC_LSI_OFF; /* Disable LSI */ RCC_OscInitStruct.LSEState = RCC_LSE_OFF; /* Disable LSE */ /*RCC_OscInitStruct.LSEDriver = RCC_LSEDRIVE_MEDIUM;*/ RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; /* Disable PLL */ RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; /* Configure oscillators */ if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { APP_ErrorHandler(); } /* Clock source configuration */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; /* Select clock types HCLK, SYSCLK, PCLK1 */ RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; /* Select HSI as the system clock */ RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; /* AHB clock not divide */ RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; /* APB clock not divided */ /* Configure clock source */ if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { APP_ErrorHandler(); } } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ void APP_ErrorHandler(void) { /* Infinite loop */ while (1) { } } /************************ (C) COPYRIGHT Puya *****END OF FILE******************/void EXTI4_15_IRQHandler(void) { smoking_tim=1000; HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_5); HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_6); HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_7); }按键按下smoking_tim为什么不变

/** ****************************************************************************** * File Name : gpio.c * Description : This file provides code for the configuration * of all used GPIO pins. ****************************************************************************** * @attention * *
© Copyright (c) 2025 STMicroelectronics. * All rights reserved.
* * 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 "gpio.h" /* USER CODE BEGIN 0 */ #include "main.h" /* USER CODE END 0 */ /*----------------------------------------------------------------------------*/ /* Configure GPIO */ /*----------------------------------------------------------------------------*/ /* USER CODE BEGIN 1 */ uint8_t uckey_down,uckey_up,uckey,uckey_old; extern float target1; extern float target2; extern float vref; extern int temp0; extern int a; /* USER CODE END 1 */ /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(ENON_GPIO_Port, ENON_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = LED2_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(LED2_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = LED1_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(LED1_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : PC10 PC11 PC12 */ GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = ENON_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(ENON_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = KEY4_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(KEY4_GPIO_Port, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); } /* USER CODE BEGIN 2 */ /*mode 1:长按值变化,松开值变为0 mode 0:按下松开后值变化,并且不变 */ uint8_t key_Scan(uint8_t mode) { if(HAL_GPIO_ReadPin(GPIOA,KEY2_Pin)== 0) uckey=1; if(HAL_GPIO_ReadPin(GPIOA,KEY3_Pin)==0) uckey=2; if(HAL_GPIO_ReadPin(GPIOA,KEY1_Pin)==0) uckey=3; uckey_down=uckey&(uckey^uckey_old); uckey_old=uckey; uint8_t key_val; if(mode==1) { if(HAL_GPIO_ReadPin(GPIOA,KEY2_Pin)== 0) key_val=1; else if(HAL_GPIO_ReadPin(GPIOA,KEY3_Pin)== 0) key_val=2; else if(HAL_GPIO_ReadPin(GPIOA,KEY1_Pin)== 0) key_val=3; else key_val=0; } if(mode==0) key_val=uckey_down; return key_val; } // 按键状态变量 volatile uint32_t key2_press_time = 0; volatile uint32_t key3_press_time = 0; volatile uint32_t key1_press_time = 0; volatile uint8_t key2_flag = 0; volatile uint8_t key3_flag = 0; volatile uint8_t key1_flag = 0; void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { uint32_t current_time = HAL_GetTick(); switch(GPIO_Pin) { case GPIO_PIN_10: // KEY2 if(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_10) == 0) { // 按下 key2_press_time = current_time; } else { // 释放 if((current_time - key2_press_time) > 20) { // 消抖 key2_flag = 1; } } break; case GPIO_PIN_11: // KEY3 if(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_11) == 0) { key3_press_time = current_time; } else { if((current_time - key3_press_time) > 20) { key3_flag = 1; } } break; case GPIO_PIN_12: // KEY1 if(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_12) == 0) { key1_press_time = current_time; } else { if((current_time - key1_press_time) > 20) { key1_flag = 1; } } break; } } /* USER CODE END 2 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ /* USER CODE BEGIN Header */ /** ****************************************************************************** *------完全开源项目------------------------- *------南阳理工学院新能源实验室------------- *------2020年6月30日--V1.0--------------------- ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "adc.h" #include "dma.h" #include "hrtim.h" #include "usart.h" #include "tim.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "mbrtu.h" #include "mbport.h" #include "key.h" #include "dr_pwm.h" #include "f_monit.h" #include "fir.h" #include "pid.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ float adc1_ture=0, adc2_ture=0, adc3_ture=0; float adc1_ture1=0, adc2_ture1=0, adc3_ture1=0; extern float target1; extern float target2; extern float vref; extern int temp0; float y=0; uint16_t ADC_IN[NUM_CHANNELS][BLOCK_SIZE]; float32_t ADC_Ot[NUM_CHANNELS][BLOCK_SIZE]; int a=0; extern volatile uint8_t key2_flag ; extern volatile uint8_t key3_flag ; extern volatile uint8_t key1_flag ; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ volatile uint32_t gSysTim01msTicks; //定时器SystemTich中断计数 volatile uint32_t ADC_Value[BuffSize];//--ADC采集8路全16位数据--- /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ void Task_05ms_A(void); void Task_05ms_B(void); void Task_05ms_C(void); void Task_05ms_D(void); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if(temp0 == 1) { y = PID_system(temp0, adc1_ture); } else { y = PID_system(temp0, adc2_ture); } // if(adc1_ture <= 2.18181) // { //// __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1,y); // } // else // { // __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1,0); // } } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ static uint16_t l_task_id; /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ //HAL_SetTickFreq(100U);//--10ms时基---- HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq));//--0.1ms时基-- /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_DMA_Init(); MX_HRTIM1_Init(); MX_ADC1_Init(); MX_ADC2_Init(); MX_LPUART1_UART_Init(); MX_TIM2_Init(); /* USER CODE BEGIN 2 */ // mb_rtu_init( &mb_port, 0x01, MB_PAR_NONE);//--Modbus初始化,设定从机为1号机,无校验位--- //------------------HRTIM启动PWM输出通道----------------------------------- HAL_NVIC_DisableIRQ(DMA1_Channel1_IRQn);//-----关闭DMA中断----- HAL_ADC_Start(&hadc2);//---先启动ADC2---注意多通道同步Cube必须设置32位字。 HAL_ADCEx_MultiModeStart_DMA(&hadc1, (uint32_t*)&ADC_Value,BuffSize);//--然后启动ADC12---注意读取高低位数据。 HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TB1 | HRTIM_OUTPUT_TB2);//----通道打开--- HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TC1 | HRTIM_OUTPUT_TC2);//----通道打开--- //---开启定时器B和C和D-使用Master完美同步--- HAL_HRTIM_WaveformCountStart_IT(&hhrtim1,HRTIM_TIMERID_MASTER | HRTIM_TIMERID_TIMER_B | HRTIM_TIMERID_TIMER_C | HRTIM_TIMERID_TIMER_D);// HAL_Delay(500); HAL_GPIO_WritePin(ENON_GPIO_Port,ENON_Pin,GPIO_PIN_SET);//--打开后级供电---- gSysTim01msTicks = 0; FreqValue = PWM_Period;//--设置频率初始值--- PhaseValue = PWM_Period/2;//--设置相位初始值-- HAL_TIM_Base_Start_IT(&htim2); // printf("MCU Temperature : %.1f\r\n",((ADC_Value[2]*3300/4096)/2.5+25)); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ // ADC_IN[0][0]=ADC_Value[0] & 0xFFFF; // for(uint8_t ch=0;ch<NUM_CHANNELS;ch++) // { // Fir_Proc(&ADC_IN[ch][0],&ADC_Ot[ch][0],ch); // } // printf("%.3f %.3f %.3f ",ADC_Ot[0][0]/4096.f*3.3f,ADC_Ot[1][0]/4096.f*3.3f,ADC_Ot[2][0]/4096.f*3.3f); // printf("%d",a); // 按键处理 if(key2_flag) { key2_flag = 0; if(temp0 == 1) { target1 = target1 - 0.1f; if(target1 < 1) target1 = 1; } a = 1; printf("KEY2 pressed. Target1: %.1f\n", target1); } if(key3_flag) { key3_flag = 0; if(temp0 == 1) { target1 = target1 + 0.1f; if(target1 > 2) target1 = 2; } a = 2; printf("KEY3 pressed. Target1: %.1f\n", target1); } if(key1_flag) { key1_flag = 0; temp0 = -temp0; a = 3; printf("KEY1 pressed. Mode: %s\n", temp0 == 1 ? "BUCK" : "BOOST"); } // if( gSysTim01msTicks >= 5 ) //每0.5ms运行一次 // { // gSysTim01msTicks = 0; // switch( l_task_id ) // { // case 0x00: //任务A,按键任务 // Task_05ms_A(); // break; // case 0x01: //任务B // Task_05ms_B(); // break; // case 0x02: //任务C // Task_05ms_C(); // break; // case 0x03: //任务D // Task_05ms_D(); // break; // } // l_task_id = l_task_id >= 0x03 ? 0 : l_task_id+1; // } } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Configure the main internal regulator output voltage */ HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV4; RCC_OscInitStruct.PLL.PLLN = 85; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { Error_Handler(); } /** Initializes the peripherals clocks */ PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_LPUART1|RCC_PERIPHCLK_ADC12; PeriphClkInit.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_PCLK1; PeriphClkInit.Adc12ClockSelection = RCC_ADC12CLKSOURCE_SYSCLK; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /******************************************************************************** * @函数: void Task_05ms_A(void) * @描述: 任务A处理函数 * 0.5ms周期调用 * 2ms中的第一个0.5ms ********************************************************************************/ void Task_05ms_A(void) { } /* ******************************************************************************* * @函数: void Task_05ms_B(void) * @描述: 任务B处理函数 * 0.5ms周期调用 * 2ms中的第二个0.5ms ******************************************************************************* */ void Task_05ms_B(void) { static uint32_t uTaskTimeCount = 0; // mb_rtu_poll( &mb_port ); // modbus协议轮询 uTaskTimeCount++; } /* ******************************************************************************* * @函数: void Task_05ms_C(void) * @描述: 任务C处理函数 * 0.5ms周期调用 * 2ms中的第三个0.5ms *----要特别小心,不要sMasterRegs.MCMP1R超过设定的PWM_Period--- *----要特别小心,尽量不使用timB的reset触发,因为有可能丢脉冲(Master Compare1 变化时,Reset信号可能错过一次)。 ******************************************************************************* */ void Task_05ms_C(void) { static uint32_t uTaskTimeCount = 0; /* 此处添加用户代码,代码执行时间应少于500us */ //--调频:50KHz - 125KHz--调相:0-180度-- gADC_V_IN = (uint16_t)( ADC_Value[0] & 0xFFFF );//---ADC1低16位--- gADC_I_IN = (uint16_t)( ADC_Value[1] & 0xFFFF ); gADC_Freq_HW = (uint16_t)( ADC_Value[2] & 0xFFFF );//---频率调节--- gADC_Chip_Temp = (uint16_t)( ADC_Value[3] & 0xFFFF ); gADC_V_OUT = (uint16_t)( ADC_Value[0] / 0xFFFF );//---ADC2高16位IN2--- gADC_I_OUT = (uint16_t)( ADC_Value[1] / 0xFFFF ); gADC_Phase_HW = (uint16_t)( ADC_Value[2] / 0xFFFF );//---相位调节--- gADC_V_NTC = (uint16_t)( ADC_Value[3] / 0xFFFF ); // FreqValue = PWM_Period + gADC_Freq_HW; dr_pwm_setFreq(FreqValue);//--设置频率 //-----------调相:250KHz----0度-133度---------------- PhaseValue = PWM_Period/2 + 0.6*gADC_Phase_HW; if (PhaseValue < PWM_Period/2) //--确保调相不超出范围 PhaseValue = PWM_Period/2; if (PhaseValue >= FreqValue) PhaseValue = FreqValue; //----------------------------------------------------- dr_pwm_setPhase(PhaseValue); //---设置相位 uTaskTimeCount++; } /* ******************************************************************************* * @函数: void Task_05ms_D(void) * @描述: 任务D处理函数 * 0.5ms周期调用 * 2ms中的第四个0.5ms ******************************************************************************* */ void Task_05ms_D(void) { static uint32_t uTaskTimeCount = 0; f_monit( );//上位机监控 /* 正常输出,闪烁5HZ指示灯 */ if(uTaskTimeCount >= 25) { uTaskTimeCount = 0; HAL_GPIO_TogglePin(LED2_GPIO_Port,LED2_Pin); } uTaskTimeCount++; } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/为什么a的值还是没改变,好像都没有进去while里的变化a的函数

* USER CODE BEGIN Header / /* @file : main.c @brief : Main program body @attention Copyright © 2025 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 “main.h” #include “can.h” #include “usart.h” #include “gpio.h” /* Private includes ----------------------------------------------------------/ / USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------/ / USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------/ / USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------/ / USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------/ void SystemClock_Config(void); / USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------/ / USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** @brief The application entry point. @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals / MX_GPIO_Init(); MX_CAN_Init(); MX_USART1_UART_Init(); / USER CODE BEGIN 2 / Uart1_Config(); printf(“串口一测试123\r\n”); / USER CODE END 2 */ /* Infinite loop / / USER CODE BEGIN WHILE / while (1) { / USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** @brief System Clock Configuration @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** @brief This function is executed in case of error occurrence. @retval None / void Error_Handler(void) { / USER CODE BEGIN Error_Handler_Debug / / User can add his own implementation to report the HAL error return state / __disable_irq(); while (1) { } / USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** @brief Reports the name of the source file and the source line number where the assert_param error has occurred. @param file: pointer to the source file name @param line: assert_param error line source number @retval None / void assert_failed(uint8_t file, uint32_t line) { / USER CODE BEGIN 6 / / 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) / / USER CODE END 6 / } #endif / USE_FULL_ASSERT / / USER CODE BEGIN Header / / @file can.c @brief This file provides code for the configuration of the CAN instances. @attention Copyright © 2025 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 “can.h” /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ CAN_HandleTypeDef hcan; /* CAN init function */ void MX_CAN_Init(void) { /* USER CODE BEGIN CAN_Init 0 */ /* USER CODE END CAN_Init 0 */ /* USER CODE BEGIN CAN_Init 1 */ /* USER CODE END CAN_Init 1 / hcan.Instance = CAN1; hcan.Init.Prescaler = 9; hcan.Init.Mode = CAN_MODE_NORMAL; hcan.Init.SyncJumpWidth = CAN_SJW_1TQ; hcan.Init.TimeSeg1 = CAN_BS1_5TQ; hcan.Init.TimeSeg2 = CAN_BS2_2TQ; hcan.Init.TimeTriggeredMode = DISABLE; hcan.Init.AutoBusOff = DISABLE; hcan.Init.AutoWakeUp = DISABLE; hcan.Init.AutoRetransmission = DISABLE; hcan.Init.ReceiveFifoLocked = DISABLE; hcan.Init.TransmitFifoPriority = DISABLE; if (HAL_CAN_Init(&hcan) != HAL_OK) { Error_Handler(); } / USER CODE BEGIN CAN_Init 2 */ /* USER CODE END CAN_Init 2 */ } void HAL_CAN_MspInit(CAN_HandleTypeDef* canHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(canHandle->Instance==CAN1) { /* USER CODE BEGIN CAN1_MspInit 0 */ /* USER CODE END CAN1_MspInit 0 / / CAN1 clock enable */ __HAL_RCC_CAN1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**CAN GPIO Configuration PA11 ------> CAN_RX PA12 ------> CAN_TX */ GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_12; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* CAN1 interrupt Init */ HAL_NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn); /* USER CODE BEGIN CAN1_MspInit 1 */ // 配置过滤器(接收所有消息) CAN_FilterTypeDef filter; filter.FilterBank = 0; filter.FilterMode = CAN_FILTERMODE_IDMASK; filter.FilterScale = CAN_FILTERSCALE_32BIT; filter.FilterIdHigh = 0x0000; filter.FilterIdLow = 0x0000; filter.FilterMaskIdHigh = 0x0000; filter.FilterMaskIdLow = 0x0000; filter.FilterFIFOAssignment = CAN_FILTER_FIFO0; filter.FilterActivation = ENABLE; HAL_CAN_ConfigFilter(&hcan, &filter); HAL_CAN_Start(&hcan); HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING); /* USER CODE END CAN1_MspInit 1 */ } } void HAL_CAN_MspDeInit(CAN_HandleTypeDef* canHandle) { if(canHandle->Instance==CAN1) { /* USER CODE BEGIN CAN1_MspDeInit 0 */ /* USER CODE END CAN1_MspDeInit 0 / / Peripheral clock disable */ __HAL_RCC_CAN1_CLK_DISABLE(); /**CAN GPIO Configuration PA11 ------> CAN_RX PA12 ------> CAN_TX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_11|GPIO_PIN_12); /* CAN1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn); /* USER CODE BEGIN CAN1_MspDeInit 1 */ /* USER CODE END CAN1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 / //数据发送函数 uint8_t CAN_Send(uint32_t id, uint8_t data, uint8_t len) { CAN_TxHeaderTypeDef txHeader; uint32_t txMailbox; txHeader.StdId = id; // 标准ID txHeader.ExtId = 0; // 扩展ID(标准帧设为0) txHeader.IDE = CAN_ID_STD; // 使用标准帧 txHeader.RTR = CAN_RTR_DATA; // 数据帧 txHeader.DLC = len; // 数据长度 txHeader.TransmitGlobalTime = DISABLE; if(HAL_CAN_AddTxMessage(&hcan, &txHeader, data, &txMailbox) != HAL_OK) { return 0; // 发送失败 } // 等待发送完成 while(HAL_CAN_GetTxMailboxesFreeLevel(&hcan) != 3); return 1; } //中断接收处理 void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) { CAN_RxHeaderTypeDef rxHeader; uint8_t rxData[8]; if(HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &rxHeader, rxData) == HAL_OK) { uint32_t id = rxHeader.StdId; // 获取标准ID uint8_t len = rxHeader.DLC; // 数据长度 // 处理接收数据 (示例: 串口转发) printf("ID:0x%X Data:", id); for(int i=0; i<len; i++) { printf("%02X ", rxData[i]); } printf("\n"); } } /* USER CODE END 1 / / USER CODE BEGIN Header / /* @file stm32f1xx_it.c @brief Interrupt Service Routines. @attention Copyright © 2025 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 “main.h” #include “stm32f1xx_it.h” / Private includes ----------------------------------------------------------/ / USER CODE BEGIN Includes / / USER CODE END Includes */ /* Private typedef -----------------------------------------------------------/ / USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------/ / USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------/ / USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------/ / USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------/ / USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------/ / USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------/ extern CAN_HandleTypeDef hcan; extern UART_HandleTypeDef huart1; / USER CODE BEGIN EV */ /* USER CODE END EV */ // / Cortex-M3 Processor Interruption and Exception Handlers / // /** @brief This function handles Non maskable interrupt. / void NMI_Handler(void) { / USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 / / USER CODE BEGIN NonMaskableInt_IRQn 1 / while (1) { } / USER CODE END NonMaskableInt_IRQn 1 */ } /** @brief This function handles Hard fault interrupt. / void HardFault_Handler(void) { / USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 / while (1) { / USER CODE BEGIN W1_HardFault_IRQn 0 / / USER CODE END W1_HardFault_IRQn 0 */ } } /** @brief This function handles Memory management fault. / void MemManage_Handler(void) { / USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 / while (1) { / USER CODE BEGIN W1_MemoryManagement_IRQn 0 / / USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** @brief This function handles Prefetch fault, memory access fault. / void BusFault_Handler(void) { / USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 / while (1) { / USER CODE BEGIN W1_BusFault_IRQn 0 / / USER CODE END W1_BusFault_IRQn 0 */ } } /** @brief This function handles Undefined instruction or illegal state. / void UsageFault_Handler(void) { / USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 / while (1) { / USER CODE BEGIN W1_UsageFault_IRQn 0 / / USER CODE END W1_UsageFault_IRQn 0 */ } } /** @brief This function handles System service call via SWI instruction. / void SVC_Handler(void) { / USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 / / USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** @brief This function handles Debug monitor. / void DebugMon_Handler(void) { / USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 / / USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** @brief This function handles Pendable request for system service. / void PendSV_Handler(void) { / USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 / / USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** @brief This function handles System tick timer. / void SysTick_Handler(void) { / USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 / HAL_IncTick(); / USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } // / STM32F1xx Peripheral Interrupt Handlers / / Add here the Interrupt Handlers for the used peripherals. / / For the available peripheral interrupt handler names, / / please refer to the startup file (startup_stm32f1xx.s). / // /** @brief This function handles USB low priority or CAN RX0 interrupts. / void USB_LP_CAN1_RX0_IRQHandler(void) { / USER CODE BEGIN USB_LP_CAN1_RX0_IRQn 0 */ /* USER CODE END USB_LP_CAN1_RX0_IRQn 0 / HAL_CAN_IRQHandler(&hcan); / USER CODE BEGIN USB_LP_CAN1_RX0_IRQn 1 */ /* USER CODE END USB_LP_CAN1_RX0_IRQn 1 */ } /** @brief This function handles USART1 global interrupt. / void USART1_IRQHandler(void) { / USER CODE BEGIN USART1_IRQn 0 / / 检查是否为接收中断(收到一个字节) / if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_RXNE) != RESET) { uint8_t data = (uint8_t)(huart1.Instance->DR); // 读取接收到的数据 USART1->DR = data;//串口回显 if (usart1_data.len < MAX - 1) // 防止溢出,保留 ‘\0’ 空间 { usart1_data.rbuff[usart1_data.len++] = data; } } / 检查是否为空闲中断(一帧数据接收完成) */ if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET) { __HAL_UART_CLEAR_IDLEFLAG(&huart1); // 清除空闲中断标志 usart1_data.rbuff[usart1_data.len] = ‘\0’; // 添加字符串结束符 usart1_data.rdflag = 1; // 设置接收完成标志 // HAL_UART_Transmit(&huart1,usart1_data.rbuff,usart1_data.len,1000); usart1_data.len = 0; // 重置长度,准备下一次接收 memset(usart1_data.rbuff, 0, usart1_data.len); usart1_data.rdflag = 0; // 可选:重启接收(如果中途停止) HAL_UART_Receive_IT(&huart1, (uint8_t )usart1_data.rbuff, 1); } / USER CODE END USART1_IRQn 0 / HAL_UART_IRQHandler(&huart1); / USER CODE BEGIN USART1_IRQn 1 */ /* USER CODE END USART1_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ 如何调用can通信的初始化,实现数据收发

大家在看

recommend-type

FastReport报表格式FRX文件转Fr3文件

FastReport报表格式FRX文件转Fr3文件
recommend-type

Excel模板企业付款申请单支付申请单模板.zip

Excel模板企业付款申请单支付申请单模板.zip
recommend-type

matlab的欧拉方法代码-BEM_flow_simulation:计算流体力学:使用边界元方法模拟障碍物周围/附近的流动

matlab的欧拉方法代码BEM_flow_simulation MATLAB上的计算流体力学: 目的是使用边界元素方法模拟任何障碍物附近或周围的任何形式的流动 使用BEM绕圆柱障碍物和接近均匀战争的潜在流动 非粘性势流的假设适用于导航斯托克斯方程(Euler方程),使用边界元方法,该代码模拟了在均匀垂直壁附近的尺寸稳定的圆柱障碍物周围的流动。 该系统不受其他方向的限制。 该代码是流体力学硕士1实习的主题,并且作为大型项目的第一块砖,该项目用于模拟复杂非均匀障碍物周围的粘性流动,因此可以自由继续。 类“ pot_flow_class”模拟垂直于垂直壁(两个障碍物之间的距离为H)附近圆柱2D障碍物(无量纲半径r = 1)附近的该势流。 流速为U = 1(无量纲)。 使用边界元素方法的第二层。 这样的流动的精确解决方案的代码允许验证无垂直壁模拟。
recommend-type

DM9051软硬件开发资料包括硬件参考设计原理图PCB+软件驱动源码及文档资料.zip

DM9051软硬件开发资料包括硬件参考设计原理图PCB+软件驱动源码及文档资料,可以作为你的学习设计参考。
recommend-type

Examples.zip

KUKA.RobotSensorInterface 4.0 说明书+例程

最新推荐

recommend-type

【scratch2.0少儿编程-游戏原型-动画-项目源码】火柴人激情格斗.zip

资源说明: 1:本资料仅用作交流学习参考,请切勿用于商业用途。更多精品资源请访问 https://blog.csdn.net/ashyyyy/article/details/146464041 2:一套精品实用scratch2.0少儿编程游戏、动画源码资源,无论是入门练手还是项目复用都超实用,省去重复开发时间,让开发少走弯路!
recommend-type

【scratch2.0少儿编程-游戏原型-动画-项目源码】环保种树,人人有责.zip

资源说明: 1:本资料仅用作交流学习参考,请切勿用于商业用途。更多精品资源请访问 https://blog.csdn.net/ashyyyy/article/details/146464041 2:一套精品实用scratch2.0少儿编程游戏、动画源码资源,无论是入门练手还是项目复用都超实用,省去重复开发时间,让开发少走弯路!
recommend-type

sparkling-water-extensions_2.12-3.46.0.6-1-3.2.jar

sparkling-water-extensions_2.12-3.46.0.6-1-3.2.jar
recommend-type

bcmpricingcalculator-jvm-1.4.34.jar

bcmpricingcalculator-jvm-1.4.34.jar
recommend-type

鹅肉第六课阿斯蒂芬估计

俄日局管理科对讲机
recommend-type

Node.js构建的运动咖啡馆RESTful API介绍

标题《sportscafeold:体育咖啡馆》指出了项目名称为“体育咖啡馆”,这个名字暗示了该项目可能是一个结合了运动和休闲主题的咖啡馆相关的网络服务平台。该项目运用了多种技术栈,核心的开发语言为JavaScript,这从标签中可以得到明确的信息。 从描述中可以提取以下知识点: 1. **Node.js**:体育咖啡馆项目使用了Node.js作为服务器端运行环境。Node.js是一个基于Chrome V8引擎的JavaScript运行环境,它能够使得JavaScript应用于服务器端开发。Node.js的事件驱动、非阻塞I/O模型使其适合处理大量并发连接,这对于RESTFUL API的构建尤为重要。 2. **Express Framework**:项目中使用了Express框架来创建RESTFUL API。Express是基于Node.js平台,快速、灵活且极简的Web应用开发框架。它提供了构建Web和移动应用的强大功能,是目前最流行的Node.js Web应用框架之一。RESTFUL API是一组遵循REST原则的应用架构,其设计宗旨是让Web服务通过HTTP协议进行通信,并且可以使用各种语言和技术实现。 3. **Mongoose ORM**:这个项目利用了Mongoose作为操作MongoDB数据库的接口。Mongoose是一个对象文档映射器(ODM),它为Node.js提供了MongoDB数据库的驱动。通过Mongoose可以定义数据模型,进行数据库操作和查询,从而简化了对MongoDB数据库的操作。 4. **Passport.js**:项目中采用了Passport.js库来实现身份验证系统。Passport是一个灵活的Node.js身份验证中间件,它支持多种验证策略,例如用户名和密码、OAuth等。它提供了标准化的方法来为用户登录提供认证,是用户认证功能的常用解决方案。 5. **版权信息**:项目的版权声明表明了Sportscafe 2015是版权所有者,这表明项目或其相关内容最早发布于2015年或之前。这可能表明该API背后有商业实体的支持或授权使用。 从【压缩包子文件的文件名称列表】中我们可以了解到,该文件的版本控制仓库使用的是“master”分支。在Git版本控制系统中,“master”分支通常用于存放当前可部署的稳定版本代码。在“master”分支上进行的更改通常都是经过测试且准备发布到生产环境的。 综上所述,我们可以知道体育咖啡馆项目是一个利用现代JavaScript技术栈搭建的后端服务。它包含了处理HTTP请求的Express框架、连接MongoDB数据库的Mongoose库和实现用户身份验证的Passport.js中间件。该项目可用于构建提供体育信息、咖啡馆菜单信息、预约服务等的Web应用或API服务,这为体育咖啡馆的营销、用户体验和数据管理提供了可能。 考虑到文档资料的提及,该项目的安装和API文档应该包含在项目资料中,可能在项目的README文件或其他说明文档中。对于项目的使用者或者开发者而言,这部分文档非常重要,因为它们可以提供详细的信息和指导,帮助用户快速部署和使用该API。 总结来说,这是一套针对体育咖啡馆相关业务的后端解决方案,它使用了流行的开源技术栈,可以灵活地应用于体育咖啡馆的网络服务中,如信息发布、在线预约、会员管理等。
recommend-type

【LNR优化与用户体验】:一文看透互操作优化如何提升用户感知

# 摘要 LNR(邻区关系优化)是提升移动通信网络性能与用户体验的关键技术。本文系统阐述了LNR优化的基本概念、理论基础与技术实现路径,构建了包括信道质量评估、干扰建模及关键性能指标分析在内的数学模型,并探讨了参数配置、邻区管理及AI与大数据在LNR优化中的应用。通过量化用户感知指标,分析了LNR优化对视频流畅度、页面加载速度及切换性能的实际改善效果,并结合典型场景验证了其优化成效。本文进一步展望了LNR技术在5G及未来网络中的发展趋势与技术挑战。
recommend-type

Java1.8 的编程语言、使用场景、版本号、厂商、是否开源、发行日期、终止日期、可替代产品、推荐产品是什么

以下是关于 **Java 1.8** 的全面信息汇总,涵盖其编程语言特性、使用场景、版本号、厂商、是否开源、发行日期、终止支持日期、可替代产品和推荐产品。 --- ## ✅ Java 1.8 综合信息表 | 项目 | 内容 | |------|------| | **编程语言** | Java | | **版本号** | Java 1.8(也称为 Java 8) | | **厂商** | Oracle、Adoptium、Amazon(Corretto)、Azul(Zulu)、Red Hat、IBM 等 | | **是否开源** | ✅ 是(OpenJDK 1.8 是开源的,Oracle
recommend-type

Java开发的教区牧民支持系统介绍

根据给定文件信息,下面将详细阐述相关知识点: ### 标题知识点 #### catecumenus-java: 教区牧民支持系统 - **Java技术栈应用**:标题提到的“catecumenus-java”表明这是一个使用Java语言开发的系统。Java是目前最流行的编程语言之一,广泛应用于企业级应用、Web开发、移动应用等,尤其是在需要跨平台运行的应用中。Java被设计为具有尽可能少的实现依赖,所以它可以在多种处理器上运行。 - **教区牧民支持系统**:从标题来看,这个系统可能面向的是教会管理或教区管理,用来支持牧民(教会领导者或牧师)的日常管理工作。具体功能可能包括教友信息管理、教区活动安排、宗教教育资料库、财务管理、教堂资源调配等。 ### 描述知识点 #### 儿茶类 - **儿茶素(Catechin)**:描述中提到的“儿茶类”可能与“catecumenus”(新信徒、教徒)有关联,暗示这个系统可能与教会或宗教教育相关。儿茶素是一类天然的多酚类化合物,常见于茶、巧克力等植物中,具有抗氧化、抗炎等多种生物活性,但在系统标题中可能并无直接关联。 - **系统版本号**:“0.0.1”表示这是一个非常初期的版本,意味着该系统可能刚刚开始开发,功能尚不完善。 ### 标签知识点 #### Java - **Java语言特点**:标签中明确提到了“Java”,这暗示了整个系统都是用Java编程语言开发的。Java的特点包括面向对象、跨平台(即一次编写,到处运行)、安全性、多线程处理能力等。系统使用Java进行开发,可能看重了这些特点,尤其是在构建可扩展、稳定的后台服务。 - **Java应用领域**:Java广泛应用于企业级应用开发中,包括Web应用程序、大型系统后台、桌面应用以及移动应用(Android)。所以,此系统可能也会涉及这些技术层面。 ### 压缩包子文件的文件名称列表知识点 #### catecumenus-java-master - **Git项目结构**:文件名称中的“master”表明了这是Git版本控制系统中的一个主分支。在Git中,“master”分支通常被用作项目的主干,是默认的开发分支,所有开发工作都是基于此分支进行的。 - **项目目录结构**:在Git项目中,“catecumenus-java”文件夹应该包含了系统的源代码、资源文件、构建脚本、文档等。文件夹可能包含各种子文件夹和文件,比如src目录存放Java源代码,lib目录存放相关依赖库,以及可能的build.xml文件用于构建过程(如Ant或Maven构建脚本)。 ### 结合以上信息的知识点整合 综合以上信息,我们可以推断“catecumenus-java: 教区牧民支持系统”是一个使用Java语言开发的系统,可能正处于初级开发阶段。这个系统可能是为了支持教会内部管理,提供信息管理、资源调度等功能。其使用Java语言的目的可能是希望利用Java的多线程处理能力、跨平台特性和强大的企业级应用支持能力,以实现一个稳定和可扩展的系统。项目结构遵循了Git版本控制的规范,并且可能采用了模块化的开发方式,各个功能模块的代码和资源文件都有序地组织在不同的子文件夹内。 该系统可能采取敏捷开发模式,随着版本号的增加,系统功能将逐步完善和丰富。由于是面向教会的内部支持系统,对系统的用户界面友好性、安全性和数据保护可能会有较高的要求。此外,考虑到宗教性质的敏感性,系统的开发和使用可能还需要遵守特定的隐私和法律法规。
recommend-type

LNR切换成功率提升秘籍:参数配置到网络策略的全面指南

# 摘要 LNR(LTE to NR)切换技术是5G网络部署中的关键环节,直接影