接上一篇无人机的学习笔记,补充一些硬件驱动的内容。本文介绍如何通过定时器产生PWM来驱动电机。用的直流有刷电机
void RCC_Configuration()
{
/*GPIO*/
RCC_APB2PeriphClockCmd(RCC_APB2PERIPH_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2PERIPH_GPIOB, ENABLE);
/*TMR*/
RCC_APB1PeriphClockCmd(RCC_APB1PERIPH_TMR3, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1PERIPH_TMR4, ENABLE);
}
//GPIO口设置
void GPIO_Configuration()
{
//main motor port, TMR3_CH1->PA6, TMR3_CH2->PA7, TMR3_CH3->PB0,TMR3_CH4->PB1
GPIO_InitStructure.GPIO_Pins = GPIO_Pins_6 | GPIO_Pins_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pins = GPIO_Pins_0 | GPIO_Pins_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//main motor port, TMR4_CH1->PB6, TMR4_CH2->PB7, TMR4_CH3->PB8,TMR4_CH4->PB9
GPIO_InitStructure.GPIO_Pins = GPIO_Pins_6 | GPIO_Pins_7 | GPIO_Pins_8 | GPIO_Pins_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
#define TMRx_CHANNLEx_INIT(T, C) TMR_OC##C##Init(T, &TMRx_OCInitStructure);
static TMR_TimerBaseInitType TMRx_baseInitStructure;
static TMR_OCInitType TMRx_OCInitStructure;
void TMRx_Clock_Init(TMR_Type *TMRx, uint32_t _DIV, uint32_t _Period)
{
TMR_Reset(TMRx);
TMR_TimeBaseStructInit(&TMRx_baseInitStructure);
TMRx_baseInitStructure.TMR_DIV = _DIV;//分频
TMRx_baseInitStructure.TMR_ClockDivision = TMR_CKD_DIV1;
TMRx_baseInitStructure.TMR_Period = _Period;//周期
TMRx_baseInitStructure.TMR_CounterMode = TMR_CounterDIR_Up;
//TMR1_baseInitStructure.TMR_RepetitionCounter = 4;
TMR_TimeBaseInit(TMRx, &TMRx_baseInitStructure);
}
void main_motor_init(uint16_t freq, uint16_t minDuty, uint16_t maxDuty)
{
freq = constrain(freq, 3, 150000);
motor_port[MAIN_MOTOR].clock_period = 1000;//频率
motor_port[MAIN_MOTOR].clock_div = (SystemCoreClock / motor_port[MAIN_MOTOR].clock_period / freq - 1);//计算分频
TMR_OCStructInit(&TMRx_OCInitStructure);
TMRx_OCInitStructure.TMR_OCMode = TMR_OCMode_PWM1;
TMRx_OCInitStructure.TMR_OutputState = TMR_OutputState_Enable;
TMRx_OCInitStructure.TMR_Pulse = 0;
TMRx_OCInitStructure.TMR_OCPolarity = TMR_OCPolarity_High;
motor_port[MAIN_MOTOR].minDuty = minDuty;
motor_port[MAIN_MOTOR].maxDuty = maxDuty;
TMRx_Clock_Init(TMR3, motor_port[MAIN_MOTOR].clock_div, motor_port[MAIN_MOTOR].clock_period);
TMRx_Clock_Init(TMR4, motor_port[MAIN_MOTOR].clock_div, motor_port[MAIN_MOTOR].clock_period);
TMRx_CHANNLEx_INIT(TMR3, 1);
TMRx_CHANNLEx_INIT(TMR3, 2);
TMRx_CHANNLEx_INIT(TMR3, 3);
TMRx_CHANNLEx_INIT(TMR3, 4);
TMRx_CHANNLEx_INIT(TMR4, 1);
TMRx_CHANNLEx_INIT(TMR4, 2);
TMRx_CHANNLEx_INIT(TMR4, 3);
TMRx_CHANNLEx_INIT(TMR4, 4);
TMR_CtrlPWMOutputs(TMR3, ENABLE);
TMR_CtrlPWMOutputs(TMR4, ENABLE);
TMR_Cmd(TMR3, ENABLE);
TMR_Cmd(TMR4, ENABLE);
}