定时器输出PWM控制电机

该代码实现了一个基于STM32F10x的电机控制系统,使用了TIM1进行PWM初始化,并通过按键控制电机1和电机2的启停及占空比调整。TIM1_PWM_Init函数用于配置定时器的周期和预分频值,Key_Scan函数读取按键状态,根据按键输入改变电机转速或切换电机运行状态。
摘要由CSDN通过智能技术生成

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;  //控制电机往某个方向转
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值