背景
有个项目需要控制一台风机的转速,使用STM8S003F3P6 输出PWM控制,这里就详细记录一下调试记录
原理图
原理图比较简单,电机接口CN3
电机接口原理图
与MCU管脚连接位置如下图
首先我们要明白电机的原理
电机 简单来说就是 实现电能与机械能相互转换的电工设备
那么我们经常使用的直流电机原理就是:
电生磁:通电导线会产生磁场 也就是电磁感应 旋转磁场带动转子转动。 电动机是由定子和转子组成,一个产生旋转磁场,一个为磁极,电机的转子(轴承)就转起来了。
这便实现了 电能->磁能->机械能的转换
下面两个图可以更直观的理解:
那么关于电机我们不做深究, 我们只需要知道,电机的本质,就是线圈 也就是电感元件
同时我们知道电感有防止电流突变的作用
关于电机HAS10227
不知道是哪个人,选型了个日本电机,手册都是日文,看起来累啊
对应管脚,大概就是控制VSP电压来调制电机转速
也就是对应CN3标号5
这里就是使用pwm调节电压,然后达到控制转速的目的
软件设计
pwm初始化,采用定时器1输出pwm
void Tim1_PWM_Init(void)
{
TIM1_DeInit();
/* Time Base configuration */
/*
TIM1_Period = 4095
TIM1_Prescaler = 0
TIM1_CounterMode = TIM1_COUNTERMODE_UP
TIM1_RepetitionCounter = 0
*/
//TIM1_TimeBaseInit(0, TIM1_COUNTERMODE_UP, 4095, 0);
TIM1_TimeBaseInit(0, TIM1_COUNTERMODE_UP, 1600 - 1, 0);//10KHZ
/* Channel 1, 2,3 and 4 Configuration in PWM mode */
/*
TIM1_OCMode = TIM1_OCMODE_PWM2
TIM1_OutputState = TIM1_OUTPUTSTATE_ENABLE
TIM1_OutputNState = TIM1_OUTPUTNSTATE_ENABLE
TIM1_Pulse = CCR1_Val
TIM1_OCPolarity = TIM1_OCPOLARITY_LOW
TIM1_OCNPolarity = TIM1_OCNPOLARITY_HIGH
TIM1_OCIdleState = TIM1_OCIDLESTATE_SET
TIM1_OCNIdleState = TIM1_OCIDLESTATE_RESET
*/
//TIM1_OC1Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE,
// CCR1_Val, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
// TIM1_OCNIDLESTATE_RESET);
/*TIM1_Pulse = CCR2_Val*/
//TIM1_OC2Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE, CCR2_Val,
// TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
// TIM1_OCNIDLESTATE_RESET);
/*The TIM1 CCR3 register value is equal to 0x3FF, so the TIM1 Channel 3 and TIM1
Channel 3N generate a PWM signal with a frequency equal to 488.28 Hz
and a duty cycle equal to:
TIM1 Channel3 duty cycle = TIM1_CCR3 / ( TIM1_Period + 1) = 25%.*/
/*TIM1_Pulse = CCR3_Val*/
TIM1_OC3Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE,
CCR3_Val, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
TIM1_OCNIDLESTATE_RESET);
/*TIM1_Pulse = CCR4_Val*/
//TIM1_OC4Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, CCR4_Val, TIM1_OCPOLARITY_LOW,
// TIM1_OCIDLESTATE_SET);
/* TIM1 counter enable */
TIM1_Cmd(ENABLE);
/* TIM1 Main Output Enable */
TIM1_CtrlPWMOutputs(DISABLE);
}
从手册中可以看到PC3为PWM的控制管脚,刚刚也是原理图设计的管脚
控制电机转速,就是调节PWM的输出,如下函数所示
void setSpeed(void)
{
CCR3_Val = ((uint16_t)1120) - ((uint16_t) 112) * (5 - speed);//最大70%,每次递减7%
TIM1->CCR3H = (uint8_t)(CCR3_Val >> 8);
TIM1->CCR3L = (uint8_t)(CCR3_Val);
TIM1_CtrlPWMOutputs(ENABLE);
}