本书采用 H_PWM-L_ON:只有上桥臂(U/V/W+)走 TIM1 的 CH1/CH2/CH3(PA8/PA9/PA10)输出 PWM 调速;下桥臂(PB13/PB14/PB15)用普通推挽 IO 直接开关。霍尔 U/V/W 接 PH10/PH11/PH12,半桥刹车 SHUTDOWN = PF10(低电平使能、高电平关断)。


定时器 ARR=10000−1、PSC=0,更新中断约 55µs(约 18kHz),最大占空比限制 MAX_PWM_DUTY=(10000-1)×0.96 限速。霍尔状态:U=bit0、V=bit1、W=bit2,组合值 1~6 有效:

uint32_t hallsensor_get_state(uint8_t motor_id)
{
__IO static uint32_t State;
State = 0;
if (motor_id == MOTOR_1) {
if (HAL_GPIO_ReadPin(HALL1_TIM_CH1_GPIO, HALL1_TIM_CH1_PIN)
!= GPIO_PIN_RESET) State |= 0x01U; /* 霍尔U -> bit0 */
if (HAL_GPIO_ReadPin(HALL1_TIM_CH2_GPIO, HALL1_TIM_CH2_PIN)
!= GPIO_PIN_RESET) State |= 0x02U; /* 霍尔V -> bit1 */
if (HAL_GPIO_ReadPin(HALL1_TIM_CH3_GPIO, HALL1_TIM_CH3_PIN)
!= GPIO_PIN_RESET) State |= 0x04U; /* 霍尔W -> bit2 */
}
return State; /* 返回 1~6 的组合值 */
}void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{ /* 周期约 55us */
if (htim->Instance == ATIM_TIMX_PWM) {
if (g_bldc_motor1.run_flag == RUN) {
if (g_bldc_motor1.dir == CW) /* 正转:霍尔顺序 6,2,3,1,5,4 */
g_bldc_motor1.step_sta = hallsensor_get_state(MOTOR_1);
else /* 反转:顺序 5,1,3,2,6,4 */
g_bldc_motor1.step_sta = 7 - hallsensor_get_state(MOTOR_1);
if ((g_bldc_motor1.step_sta <= 6) &&
(g_bldc_motor1.step_sta >= 1))
pfunclist_m1[g_bldc_motor1.step_sta - 1](); /* 查表换相 */
else { /* 霍尔错误/接触不良则停机 */
stop_motor1();
g_bldc_motor1.run_flag = STOP;
}
}
}
}12~60V DC 电源(建议 24V 额定)。按键:KEY0 每按一次占空比 +500(加速),KEY1 −500(减到负值自动换向),KEY2 停机清零;LCD 显示当前占空比百分比。启动调用 bldc_init(10000-1, 0) 与 bldc_ctrl(MOTOR_1, CCW, 0) 后开定时器。