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"
#include "motor.h"
void motor_init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
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);
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);
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);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
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);
TIM_SetCompare4(TIM4, L_speed);
}
#include "stm32f10x.h"
#include "motor.h"
int main()
{
motor_init();
car_go();
car_speed_set(65, 65);
while(1);
}