今天学习的是PWM波,PWM波就是占空比以下是我用STM32配置的PWM程序
int PWM_GPIO()
{
GPIO_InitTypeDef GPIO_PWM;
TIM_TimeBaseInitTypeDef TIM_PWM;
TIM_OCInitTypeDef TIM_OC_PWM;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
RCC_APB2PeriphClockCmd( RCC_APB2Periph_AFIO, ENABLE);
GPIO_PWM.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_PWM.GPIO_Pin = GPIO_Pin_0;
GPIO_PWM.GPIO_Speed = GPIO_Speed_50MHz;
TIM_PWM.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_PWM.TIM_CounterMode = TIM_CounterMode_Up;
TIM_PWM.TIM_Period = 200-1;
TIM_PWM.TIM_Prescaler = 7200-1;
TIM_OC_PWM.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式1
TIM_OC_PWM.TIM_OutputState = TIM_OutputState_Enable; //比较使出使能
TIM_OC_PWM.TIM_OCPolarity = TIM_OCPolarity_Low; //选择有效输出极性
GPIO_Init(GPIOB,&GPIO_PWM);
TIM_TimeBaseInit(TIM3,&TIM_PWM);
TIM_OC3Init(TIM3,&TIM_OC_PWM);
TIM_Cmd(TIM3,ENABLE);
TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);
}
一共需要配置的是GPIO和中断定时器以及PWM其中GPIO是复用的GPIO,
写主函数的程序
#include "stm32f10x.h"
#include "main.h"
#include "usart.h"
#include "time.h"
#include "PWM.h"
void delay(uint16_t time)
{
uint16_t i=0;
while(time --)
{
i=12000;
while(i--);
}
}
int main()
{
uint16_t i= 155;
PWM_GPIO();
while(1)
{
for(i=195;i>=175;i-=5)
{
TIM_SetCompare3(TIM3,i);
delay(100);
}
}
}