STM32 用定时器产生1Mhz 脉冲,PWM宽度可调,四路输出
源码:记得要加入文件 gpio rcc tim 等c文件
#include "stm32f10x_conf.h"
void GPIO_CFG(void);
void RCC_CFG(void);
void TIM_CFG(void);
void NVIC_Configuration(void);
int main (void)
{
RCC_CFG();
NVIC_Configuration();
GPIO_CFG();
TIM_CFG();
TIM_Cmd(TIM3,ENABLE);
TIM_CtrlPWMOutputs(TIM3,ENABLE);
//while(1);
}
void RCC_CFG(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
}
void GPIO_CFG(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
void TIM_CFG(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// TIM_Period 计数值,比如 TIM_Period=17 分频参数 TIM_Prescaler=3 (0为不分频),APB1 时钟是72Mhz,
//在本参数情况下, 72Mhz/(17+1)/(3+1)= 1Mhz
// 理论最大频率是 72/(1+1)/1=36Mhz TIM_Period=1 TIM_Prescaler=0 ,产生的方波可能是三角形的,用模拟示波器才能看出来,数字逻辑分析仪看不错,
// 5Mhz以内的方波应该没问题,如果要产生高频率的方波,感觉应该用SPI的数据时钟来实现
TIM_TimeBaseStructure.TIM_Period=17; // TIM_Period=70; TIM_Prescaler=0; 输出1Mhz时钟
TIM_TimeBaseStructure.TIM_Prescaler=3;
TIM_TimeBaseStructure.TIM_ClockDivision=0x00;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0x00;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
// TIM_Pulse的值不可大于TIM_Period
TIM_OCInitStructure.TIM_Pulse=60; //PA.6
TIM_OC1Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=35; //PA.7
TIM_OC2Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=18; //PB.0
TIM_OC3Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=9; //PB.1
TIM_OC4Init(TIM3,&TIM_OCInitStructure);
}
|