一、知识补充;
低频时有蜂鸣器响声,加大PWM频率,超出人耳范围就可以听不到,20Hz~20kHz
加大频率-->减小预分频器,从720-->36现在频率就是20kHz这样不会影响占空比?
二、接线图
三、代码分析
main,c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Motor.h"
#include "Key.h"
uint8_t KeyNum;
int8_t Speed;
int main(void)
{
OLED_Init();
Motor_Init();
Key_Init();
OLED_ShowString(1,1,"Speed:");
while(1)
{
KeyNum = Key_GetNum();
if(KeyNum == 1)
{
Speed += 20;
if(Speed > 100)
{
Speed = -100;
}
}
Motor_SetSpeed(Speed);
OLED_ShowSignedNum(1,7,Speed,3);
}
}
motor.c
#include "stm32f10x.h" // Device header
#include "PWM.h"
void Motor_Init(void)
{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode= GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
PWM_Init();
}
void Motor_SetSpeed(int8_t Speed)
{
if(Speed >= 0)//正转 此处为逆时针,可以改接线或者对调Set REset
{
GPIO_SetBits(GPIOA,GPIO_Pin_4);
GPIO_ResetBits(GPIOA,GPIO_Pin_5);
PWM_SetCompare3(Speed);
}
else//反转 顺时针
{
GPIO_ResetBits(GPIOA,GPIO_Pin_4);
GPIO_SetBits(GPIOA,GPIO_Pin_5);
PWM_SetCompare3(-Speed);//setcompare必须传正数
}
}
PWM.c
此处变动:接PA2通道 为CH3 频率改高
#include "stm32f10x.h" // Device header
void PWM_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//一般使用输出数据寄存器控制
//想让定时器控制
//就要复用输出,输出控制权转移给片上外设
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;//查找引脚定义知,TIM2_CH1_ETR在PA0口
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
TIM_InternalClockConfig(TIM2);//选择时基单元时钟源,上电默认使用内部时钟,不写也行
/*****时基单元初始化*****/
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision =TIM_CKD_DIV1;//一分频
TIM_TimeBaseInitStructure.TIM_CounterMode =TIM_CounterMode_Up ;//向上计数
TIM_TimeBaseInitStructure.TIM_Period = 100 - 1;//ARR的值
TIM_TimeBaseInitStructure.TIM_Prescaler = 36 - 1 ;//PSC 20kHz
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;//重复计数器(高级计数器才有)
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCStructInit(&TIM_OCInitStructure);//总结:赋一个初始值
//下面再改自己想改的参数
//防止配置通用定时器时未配置全部结构体成员导致改为高级定时器时出现错误
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//输出模式
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//输出极性
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//输出使能
TIM_OCInitStructure.TIM_Pulse = 0 ;//初始化CCR
TIM_OC3Init( TIM2,&TIM_OCInitStructure);
TIM_Cmd(TIM2,ENABLE);
}
void PWM_SetCompare3(uint16_t Compare)
{
TIM_SetCompare3(TIM2,Compare);
}