#include "stm32f10x.h" // Device header void TIM1_PWM_Enable(void) { TIM1->CCER |= 0x0005; // 使能输出 } void TIM1_PWM_Disable(void) { TIM1->CCER &= ~0x0005;//必须得让互补的两位复位,使用0x0001的话在复位后第一次按下时还会出现一次高电平 } int main(void) { // 结构体声明 GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;//时基结构体, TIM_OCInitTypeDef TIM_OCInitStructure; TIM_BDTRInitTypeDef TIM_BDTRStructure; // 时钟使能 RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE); //TIM1时钟使能 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOA, ENABLE); //使能PORTE时钟 // IO配置 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度100MHz GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PA8 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; GPIO_Init(GPIOB,&GPIO_InitStructure); //初始化PB13 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_Init(GPIOA,&GPIO_InitStructure); // 定时器配置 TIM_TimeBaseStructure.TIM_Prescaler=1-1; //定时器分频72/1=72M TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式 TIM_TimeBaseStructure.TIM_Period=150-1; //自动重装载值72M / 350 =480KHz 2.0833us TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; /*禁用重复计数器*/ TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure);//初始化定时器1 // 定时器比较输出通道配置 TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //输出使能 TIM_OCInitStructure.TIM_OutputNState=TIM_OutputNState_Enable; //互补输出使能 TIM_OCInitStructure.TIM_Pulse=74; //占空比:初始化 TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High; //输出极性高 TIM_OCInitStructure.TIM_OCNPolarity=TIM_OCNPolarity_High; // 互补端输出极性高 TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Reset; // 输出空闲电平低 TIM_OCInitStructure.TIM_OCNIdleState=TIM_OCNIdleState_Reset; //互补输出空闲电平低 TIM_OC1Init(TIM1, &TIM_OCInitStructure); // OC1 TIM_OC1PreloadConfig(TIM1,TIM_OCPreload_Enable); //开启预装载,在更新时间后才会重新装载数值 // 刹车死区配置 TIM_BDTRStructure.TIM_OSSRState=TIM_OSSRState_Disable; //运行模式下“关闭状态“选择 TIM_BDTRStructure.TIM_OSSIState=TIM_OSSIState_Disable; //空闲模式下“关闭状态“选择 TIM_BDTRStructure.TIM_LOCKLevel=TIM_LOCKLevel_OFF;// 写保护锁,不锁,锁住的话电平会来回跳动,我也没搞懂,大佬帮忙指教下 TIM_BDTRStructure.TIM_DeadTime=0x0A; //DT = 10*2.0833us = 20.833us TIM_BDTRStructure.TIM_Break=TIM_Break_Disable;//失能刹车输入 TIM_BDTRStructure.TIM_BreakPolarity=TIM_BreakPolarity_High; //刹车输入管脚极性高 TIM_BDTRStructure.TIM_AutomaticOutput=TIM_AutomaticOutput_Enable;// 自动输出功能使能 TIM_BDTRConfig(TIM1,&TIM_BDTRStructure); TIM_ARRPreloadConfig(TIM1,ENABLE);//ARPE使能 TIM_Cmd(TIM1, ENABLE); //使能TIM1 TIM_CtrlPWMOutputs(TIM1, ENABLE); //开启OC和OCN输出 while (1) { uint16_t key = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4); if(key == Bit_RESET)//按下按键停止互补PWM输出 { TIM1_PWM_Disable();//测试正常如图1-1 } else { TIM1_PWM_Enable(); } } }
按键按下后