STM32 pwm 小车前进实现

stm32 pwm

脉冲宽度调制
可以修改占空比的脉冲波,周期时间不变
占空比:有效电平时间与周期时间比例
有效电平:由外设决定

利用三极管的基极,将pwm 3.3v接在基极,集电极接12v,高电平触发使得发射极接通12v,而基极的高电平占空比决定了发射极持续的时间

基于stm32实现小车前进

#ifndef __MOTOR_H
#define __MOTOR_H

void motor_init(void);
void car_go(void);
void car_speed_set(int L_speed, int R_speed);

#endif
#include "stm32f10x.h"                  // Device header
#include "motor.h"

/*********************
驱动板     stm32
  VM    --  5V  
  VCC   --  3.3V
  GND   --  GND 

  AIN1  --  PB12
  AIN2  --  PB13
  BIN1  --  PB14
  BIN2  --  PB15

  PWMA  --  PB8  定时器4 通道3    右轮
  PWMB  --  PB9  定时器4 通道4    左轮
***********************/

void motor_init(void)
{
	//1.打开时钟,TIM4, GPIOB
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	

	//2.设置GPIO模式
	//PB12~PB15 通用推挽输出
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 |GPIO_Pin_14 |GPIO_Pin_15;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	//PB8,PB9 复用推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	//初始化TIM4 100us
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_Period = 99;
	TIM_TimeBaseInitStructure.TIM_Prescaler = 71;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = 0x0;
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure);
	
	//初始化PWM波形
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCInitStructure.TIM_Pulse = 0;//比较值初始值 占空比0
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//极性高,高电平为有效电平
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//PWM模式1,低于ORR时为有效电平
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//输出使能
	TIM_OC3Init(TIM4, &TIM_OCInitStructure);//初始化右轮
	TIM_OC4Init(TIM4, &TIM_OCInitStructure);//初始化左轮
	
	//使能定时器
	TIM_Cmd(TIM4, ENABLE);

}
void car_go(void)
{
	GPIO_ResetBits(GPIOB, GPIO_Pin_12);//输出低电平
	GPIO_SetBits(GPIOB, GPIO_Pin_13);//输出高电平
	GPIO_ResetBits(GPIOB, GPIO_Pin_14);//输出低电平
	GPIO_SetBits(GPIOB, GPIO_Pin_15);//输出高电平
}
void car_speed_set(int L_speed, int R_speed)
{
	//限制幅度
	if(L_speed > 99)
		L_speed = 99;
	if(R_speed > 99)
		R_speed = 99;
	

	TIM_SetCompare3(TIM4, R_speed);//修改ORR
	TIM_SetCompare4(TIM4, L_speed);

}
#include "stm32f10x.h"                  // Device header
#include "motor.h"

int main()
{
	motor_init();
	car_go();
	car_speed_set(65, 65);

	while(1);

}

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