在线时间0 小时
UID102921
ST金币0
蝴蝶豆0
注册时间2008-6-16
新手上路
- 最后登录
- 1970-1-1
|
a0a.1 0b0c
stm32之pwm
#include "stm32f10x.h"
#include"stm32f10x_tim.h"
#include"stm32f10x_rcc.h"
void RCC_Configuration(void);
void GPIO_Configuration(void);
void TIM_Configuration(void);
int main(void)
{
{
RCC_Configuration();
GPIO_Configuration();
TIM_Configuration();
}
}
void TIM_Configuration()
{
TIM_TimeBaseInitTypeDef TIM_BaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_DeInit(TIM1); //重设为缺省值
//tim初始设置
TIM_BaseInitStructure.TIM_Prescaler =4000;//预分频(时钟分频)72M/4000=18K
TIM_BaseInitStructure.TIM_Period = 10000;//装载值 18k/144=1.8hz 就是说向上加的10000便满了
TIM_BaseInitStructure.TIM_ClockDivision = 0;
TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上加
TIM_BaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_BaseInitStructure);
TIM_ARRPreloadConfig(TIM1, ENABLE); //启用ARR的影子寄存器(直到产生更新事件才更改设置)
//TIM1_OC1模块设置(设置1通道占空比)
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//正向通道有效
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //反向通道也有效
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; //互补端的极性
TIM_OCInitStructure.TIM_Pulse = 5000; //占空时间 10000中有5000的时间为低,互补的输出正好相反
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable); //启用CCR1寄存器的影子寄存器(直到产生更新事件才更改设置)
//TIM2_OC2模块设置(设置2通道占空比)
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
TIM_OCInitStructure.TIM_Pulse = 1000;
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable); //启用CCR2寄存器的影子寄存器(直到产生更新事件才更改设置)
TIM_Cmd(TIM1, ENABLE); //TIM1开启
TIM_CtrlPWMOutputs(TIM1, ENABLE); //TIM1_OC通道输出PWM(一定要加)
}
void RCC_Configuration()
{
RCC_DeInit();
RCC_HSEConfig(RCC_HSE_ON);
RCC_HCLKConfig(RCC_SYSCLK_Div1);
RCC_PCLK2Config(RCC_HCLK_Div1);
RCC_PCLK1Config(RCC_HCLK_Div2);
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
RCC_PLLCmd(ENABLE);
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB ,ENABLE); //开启相应端口时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); //启动AFIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); //启动TIM1
}
void GPIO_Configuration()
{
GPIO_InitTypeDef GPIO_InitStructure;
//GPIO做相应设置,为AF输出
//PA.8/9口设置为TIM1的OC1输出口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//PB.13/14口设置为TIM1_CH1N和TIM1_CH2N输出口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
|
|