Files
Gamble/MPU6050/APP/pwm.c
2023-12-18 14:36:22 +08:00

81 lines
2.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "pwm.h"
void TIM2_PWM_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //使能TIM2时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); //使能GPIOA时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_14;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
//配置PA1PA2为复用输出模式输出速度为50MHZ
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//开启TIM2内部时钟
TIM_InternalClockConfig(TIM2);
//配置TIM2
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分频
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数方式向上计数
TIM_TimeBaseInitStructure.TIM_Period = 1440 - 1; //ARR 自动重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1; //PSC 预分频器
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;//配置PWM模式1
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//有效极性为高电平
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR
TIM_OC1Init(TIM2, &TIM_OCInitStructure); //初始化通道1 PA0
TIM_OC2Init(TIM2, &TIM_OCInitStructure); //初始化通道2 PA1
TIM_OC3Init(TIM2, &TIM_OCInitStructure); //初始化通道3 PA2
TIM_Cmd(TIM2, ENABLE); //使能定时器2
}
void TIM4_1ms_Init(void) //(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);
NVIC_InitStructure.NVIC_IRQChannel=TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_TimeBaseInitStructure.TIM_Period = 1000-1; //1ms
TIM_TimeBaseInitStructure.TIM_Prescaler= 72-1; //72分频=1MHz
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStructure);
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE);
TIM_Cmd(TIM4,ENABLE);
}
uint32_t time1_cntr;
uint32_t time2_cntr;
//定时器中断服务函数
void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4,TIM_IT_Update)==SET) //溢出中断
{
time1_cntr++;
time2_cntr++;
}
TIM_ClearITPendingBit(TIM4,TIM_IT_Update); //清除中断标志位
}