本帖最后由 地瓜patch 于 2026-9-2 21:17 编辑
接上贴,继续未完成的点灯。
CubeMX2生成的工程还是有个熟悉过程的。
MX2生成的工程树如下图。
其生成的main.c文件极为简单, main() 非常干净,调用mx_system_init()函数,然后就是while (1) {}。
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private functions prototype -----------------------------------------------*/
/**
* brief: The application entry point.
* retval: none but we specify int to comply with C99 standard
*/
int main(void)
{
/** System Init: this code placed in targets folder initializes your system.
* It calls the initialization (and sets the initial configuration) of the peripherals.
* You can use STM32CubeMX to generate and call this code or not in this project.
* It also contains the HAL initialization and the initial clock configuration.
*/
if (mx_system_init() != SYSTEM_OK)
{
return (-1);
}
else
{
/*
* You can start your application code here
*/
while (1) {}
}
} /* end main */
mx_system_init()函数在mx_system.c中定义。在mx_system_init()函数有如下说明,mx_tim1_init()在mx_tim1.c中声明。
/** TIM1: mx_tim1_init() has been generated,
* but it is expected that application will call it when best needed
* according to application needs.
* See Cube code generator options: Generate and call Initialization function
*/
目标是实现LED1的呼吸灯效果,在这个基础上改。需要做 3 件事:手动调用 mx_tim1_init();配 PA5 = AF2(GPIO 复用);启动 TIM1实现呼吸循环。
首先,初始化TIM1,
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
hal_tim_handle_t *htim1 = mx_tim1_init();
if (htim1 == NULL)
{
while (1); // ?????,??
}
mx_tim1_init()函数中用 HAL2 的方式初始化 hTIM1 句柄,绑定 HAL_TIM1 这个外设标识。返回 hal_tim_handle_t*。并开启 TIM1 时钟,配定时器基本参数包括分频参数,计数方式等。配 CH3 为 PWM mode 1,初始 pulse = 0x200。
其次,将PA5映射到TIM1_CH3。
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_5, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_5, 2); // AF1
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_5, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_5, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_5, LL_GPIO_PULL_NO);
再次,使能TIM1_CH3输出
LL_TIM_CC_EnableChannel(TIM1, LL_TIM_CHANNEL_CH3); // CC3E
LL_TIM_EnableAllOutputs(TIM1); // MOE,??
LL_TIM_EnableCounter(TIM1); // CEN
最后,就是配置初始化参数,计数初值
uint32_t arr = LL_TIM_GetAutoReload(TIM1); // 0xFFFF
int32_t pwm = 0x200;
int32_t step = 300;
/* USER CODE END 2 */
while (1)
{
/* USER CODE BEGIN WHILE */
LL_TIM_OC_SetCompareCH3(TIM1, (uint32_t)pwm);
pwm += step;
if (pwm >= (int32_t)arr)
{
pwm = (int32_t)arr;
step = -100;
}
else if (pwm <= 0)
{
pwm = 0;
step = 100;
}
HAL_Delay(1);
/* USER CODE END WHILE */
}
经过以上定时器的参数配置,就可以实现呼吸灯效果。想要改变呼吸效果的话,改变while()中的 step 赋值,其绝对值越大,呼吸效果越快。反之更慢。
呼吸效果视频如下:
Stm32CubeMX2生成的MDK工程如下:
stm32c5_Led_open-cmsis.zip
(17.09 MB, 下载次数: 0)
|
|