使用STM32MIN开发板操作,对电机进行PWM简单调速,使用通用定时器TIM3上,下图为MIN板定时器引脚分布图
mian.c
#include "delay.h"
#include "usart.h"
#include "motor.h"
int main(void)
{
delay_init(); //延迟函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //中断优先级分组设置
uart_init(115200); //串口初始化设置
TIM3_PWM_Init(450,7199); //PWM输出初始化
while(1)
{
//设置通道2的占空比实现PWM调速,这里是100,在0~450间,越小速度越快
TIM_SetCompare2(TIM3,300);
P5_HIGH;
P4_LOW;
}
}
motor.c
#include "motor.h"
#include "usart.h"
//TIM3 PWM部分初始化
//PWM输出初始化
//arr:自动重装载值
//psc 时钟预分频系数
void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能定时器3时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIO外设时钟
//初始化IOPA4
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_ResetBits(GPIOA,GPIO_Pin_4);
//初始化IOPA5
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_ResetBits(GPIOA,GPIO_Pin_5);
//初始化IOPA7
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//初始化TIM3,
TIM_TimeBaseStructure.TIM_Period = arr; //自动重装载值
TIM_TimeBaseStructure.TIM_Prescaler =psc; //预分频系数
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
//初始化TIM3 Channel2
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low ; //输出比较极性地
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); //使能定时器3通道2预装载寄存器
TIM_Cmd(TIM3, ENABLE); //使能TIM3
}
motor.h
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
#define P4 GPIO_Pin_4
#define P5 GPIO_Pin_5
//#define MORTOR_PROT GPIOA
#define P4_LOW GPIO_ResetBits(GPIOA,P4)
#define P4_HIGH GPIO_SetBits(GPIOA,P4)
#define P5_LOW GPIO_ResetBits(GPIOA,P5)
#define P5_HIGH GPIO_SetBits(GPIOA,P5)
void TIM3_PWM_Init(u16 arr,u16 psc);
#endif