TIM — TIM1_6Step
固件库: PY32L020_Firmware V1.2.1
芯片: PUYA
源文件: PUYA/PY32L020_Firmware_V1.2.1/Projects/PY32L020-STK/Example/TIM/TIM1_6Step/Src/main.c
功能简介
本示例演示定时器 6 步换相功能。这是无刷直流电机(BLDC)驱动的核心技术,通过 6 个功率管按顺序导通实现电机旋转。
完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#include "main.h"
int main(void)
{
/* Reset of all peripherals, Initializes the Systick. */
HAL_Init();
TimHandle.Instance = TIM1; /* TIM1 */
TimHandle.Init.Period = 100 - 1; /* Period = 100 - 1 */
TimHandle.Init.Prescaler = 24 - 1; /* Prescaler = 24 - 1 */
TimHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; /* ClockDivision = 0 */
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; /* Counter direction = Up */
TimHandle.Init.RepetitionCounter = 1 - 1; /* Repetition = 0 */
TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; /* Auto-reload register not buffered */
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK) /* Initialize TIM1 */
{
APP_ErrorHandler();
}
/* PWM Config */
sConfig1.OCMode = TIM_OCMODE_TIMING; /* Channel Mode: TIMING */
sConfig1.OCPolarity = TIM_OCPOLARITY_HIGH; /* Channel effective polarity: high level */
sConfig1.OCNPolarity = TIM_OCNPOLARITY_HIGH; /* Complementary channel effective polarity: high level */
sConfig1.OCIdleState = TIM_OCIDLESTATE_RESET; /* Channel idle state: low level */
sConfig1.OCNIdleState = TIM_OCNIDLESTATE_RESET; /* Complementary channel idle state: low level */
sConfig1.OCFastMode = TIM_OCFAST_DISABLE; /* Disable OC Fast Mode */
/* Configure Channel 1 Comparison Value 50 */
sConfig1.Pulse = 50 - 1;
/* Configure TIM1 Channel1 */
if (HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig1, TIM_CHANNEL_1) != HAL_OK)
{
APP_ErrorHandler();
}
sConfig2 = sConfig1;
/* Configure Channel 2 Comparison Value 50 */
sConfig2.Pulse = 50 - 1;
/* Configure TIM1 Channel2 */
if (HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig2, TIM_CHANNEL_2) != HAL_OK)
{
APP_ErrorHandler();
}
sConfig3 = sConfig1;
/* Configure Channel 3 Comparison Value 50 */
sConfig3.Pulse = 50 - 1;
/* Configure TIM1 Channel3 */
if (HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig3, TIM_CHANNEL_3) != HAL_OK)
{
APP_ErrorHandler();
}
/* Configuring commutation events: software mode */
HAL_TIMEx_ConfigCommutEvent_IT(&TimHandle, TIM_TS_NONE, TIM_COMMUTATION_SOFTWARE);
while (1)
{
}
}
|
代码讲解
板级初始化:初始化开发板上的 LED、按键等基础外设。
定时器配置:设置预分频器(PSC)和重装载值(ARR),定时时间 = (PSC+1) × (ARR+1) / 时钟频率。
PWM 配置:在定时器基础上设置比较值(CCR),占空比 = CCR / (ARR+1)。CCR 越大占空比越高。