main.c
#include <stm32f10x.h>
#include "led.h"
#include "pwm.h"
#include "delay.h"
#include "usart.h"
#include "sys.h"
int main(void)
{
SysTick_Init(72);
PWM_TIM3_CH1_Init(19999,71);
// PWM_TIM3_CH2_Init(19999,71);
uart_init(9600);
LED_Init();
while(1)
{
// //改变占空比值
TIM_SetCompare1(TIM3,2500);//1500/20000=1.5/20
delay_ms(1200);
delay_ms(1200);
TIM_SetCompare1(TIM3,1000);//1000/20000=1/20
delay_ms(1200);
delay_ms(1200);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pwm.c
#include "pwm.h"
void PWM_TIM3_CH1_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TimOCInitStructure;
//1,开启 TIM4 GPIOB 复用时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO,ENABLE);
//2,初始化PB7,复用功能
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; //选择引脚7
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //输出频率最大50MHz
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA,&GPIO_InitStructure);
//3,初始化TIM4
TIM_TimeBaseStructure.TIM_Prescaler = psc; //设置定时器的分频值:1MHZ
TIM_TimeBaseStructure.TIM_Period = arr; //设置计数溢出大小 周期为500us
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //设置计数器模式为向上计数模式(+1)
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1; //分频因子
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
//4,初始化PWM输出配置,TIM4的CH2
TimOCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//PWM模式1输出
//TimOCInitStructure.TIM_Pulse = 0; //设置比较寄存中的初值(占空比)
TimOCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//TIM输出比较极性高
TimOCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//使能输出状态
TIM_OC1Init(TIM3, &TimOCInitStructure);
//TIM_OC2Init(TIM3, &TimOCInitStructure);
//5,使能TIM4预装载寄存器
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
//TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
//6,使能自动重装载
//TIM_ARRPreloadConfig(TIM4,ENABLE);
//7,使能TIM4的PWM输出
//TIM_CtrlPWMOutputs(TIM4,ENABLE);
//8,开启TIM4定时器
TIM_Cmd(TIM3, ENABLE);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pwm.h
#ifndef __PWM_H
#define __PWM_H
#include <stm32f10x.h>
void PWM_TIM3_CH1_Init(u16 arr,u16 psc);
#endif
水平不足,仅供参考:
PWM1程序.7z
(177.4 KB, 下载次数: 62)
|