main.c:
#include "stm32f10x.h"
#include "motor.h"
#include "timer.h"
#include "delay.h"
#include "key.h"
int main()
{
u16 temp = 0;
Motor_Init();
TIM1_PWM_Init(4999, 71); //arr这个参数用于确定占空比有关
Key_Init();
while(1)
{
temp = Key_Scan();
switch(temp)
{
case 1:
MOTOR1 = 1;
MOTOR2 = 0;
break;
case 2:
MOTOR1 = 0;
MOTOR2 = 1;
break;
case 3:
temp += 500;
if(temp > 4999) temp = 4999;
TIM_SetCompare1(TIM1, temp); //这里的参数和TIM1_PWM_Init的第一个参数来确定占空比
break;
case 4:
temp -= 500;
TIM_SetCompare1(TIM1, temp);
break;
}
}
}
timer.h:
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
void TIM1_PWM_Init(u16 arr, u16 psc);
#endif
timer.c:
#include "timer.h"
void TIM1_PWM_Init(u16 arr, u16 psc)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, & TIM_TimeBaseStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM工作模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_Pulse = 0; //设置预装载脉冲数值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_CtrlPWMOutputs(TIM1, ENABLE); //MOE 主输出使能
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable); //CH1预装载使能
TIM_ARRPreloadConfig(TIM1, ENABLE); //使能TIMx在ARR上的预装寄存器
TIM_Cmd(TIM1, ENABLE); //使能定时器1
}
motor.h:
#ifndef __MOTOR_H
#define __MOTOR_H
#include "sys.h"
#define MOTOR1 PBout(13)
#define MOTOR2 PBout(14)
void Motor_Init(void);
#endif
motor.c:
#include "stm32f10x.h"
#include "motor.h"
void Motor_Init()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure);
MOTOR1 = 1;
MOTOR2 = 0; //控制电机往某个方向转
}