STM32F407ZGT6控制舵机(采用通用定时器2)

调试过程,出现舵机一直来回旋转,结果把DAP烧录器一拔,就正常了。估计是烧录器不稳定。

#include "stm32f4xx.h"
#include "led.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "beep.h"
#include "key.h"
#include "rotate_servomotor.h"
#include "step_motor.h"
#include "basetimx.h"
#include "waterpump.h" 
#include "electromagnet.h" 



int main(void) 
{
	delay_init(168); 
	PWM_Init();
	
	
	while(1)
	{
		PWM_SetCompare1(500);
		delay_ms(1000); 
		PWM_SetCompare1(2500);
		delay_ms(1000); 
	}
		

}
#ifndef _STEP_MOTOR_H
#define _STEP_MOTOR_H
#include "sys.h"
#include "stm32f4xx_tim.h"  
//舵机
extern u16 arr,psc,ccr;

void PWM_Init(void);
void PWM_SetCompare1(uint16_t  compare);
void PWM_SetCompare2(uint16_t  compare);

#endif

#include "stm32f4xx.h"
#include "step_motor.h"
//#include "stm32f4xx_rcc.h"

//舵机

u16 arr=20000-1,psc=72-1,ccr=0;


void PWM_Init(void)
{
	GPIO_InitTypeDef  GPIO_InitStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);  	//TIM2时钟使能 
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);// GPIOC 	/* 指定引脚复用功能 */
 
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM2);//记得复用引脚至定时器2
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM2);//相对于开定时器2的通道1,2
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);	

	TIM_InternalClockConfig(TIM2);
	

	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; 
	TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
	TIM_TimeBaseStructure.TIM_Period = arr;   //自动重装载值
	TIM_TimeBaseStructure.TIM_Prescaler = psc;  //定时器分频
	TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;  //定时器分频
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);//初始化定时器2
	 
	
//	TIM_OCInitStructInit(&TIM_OCInitStructure);
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
 	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
	TIM_OCInitStructure.TIM_Pulse = ccr; //设置待装入捕获比较寄存器的脉冲值
	TIM_OC1Init(TIM2, &TIM_OCInitStructure);  
	TIM_OC2Init(TIM2, &TIM_OCInitStructure);  

	TIM_Cmd(TIM2, ENABLE);
}

void PWM_SetCompare1(uint16_t  Compare)
{
	TIM_SetCompare1(TIM2,Compare);
}

void PWM_SetCompare2(uint16_t  Compare)
{
	TIM_SetCompare2(TIM2,Compare);
}

你可能感兴趣的:(STM32单片机,stm32,单片机,嵌入式硬件)