每次按下按键改变TIM_Setcompare函数中占空比值即可。
相关io口,占空比调节级数,是否支持连按根据自己需要自行修改。
main.c
#include "delay.h"
#include "sys.h"
#include "pwm.h"
#include "stm32f10x_tim.h"
#include "key.h"
int t=50;//占空比
void key_function(void)
{
static u8 key = 0;
key = KEY_Scan(0);
if(key)
{
t=t+25;
if(t==125) //占空比50,75,100三档调节
{
t=50; //复位
}
}
}
void Device_Init(void) //初始化
{
delay_init();
key_Config();
delay_ms(10);
}
int main(void)
{
SystemInit(); // 配置系统时钟为72M
TIM4_PWM_Init(100,720);
Device_Init();
while(1)
{
delay_ms(10);
key_function();
TIM_SetCompare2(TIM4,t);
}
}
文章来源地址https://www.toymoban.com/news/detail-481239.html
pwm.c
#include "sys.h"
#include "pwm.h"
#include "stm32f10x_tim.h"
void TIM4_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef TIM4_PWM_Pin;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM4_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //使能定时器4时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //使能GPIO外设功能模块时钟
TIM4_PWM_Pin.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
TIM4_PWM_Pin.GPIO_Pin = GPIO_Pin_7; //PB7
TIM4_PWM_Pin.GPIO_Speed = GPIO_Speed_50MHz; //50MHZ
GPIO_Init(GPIOB,&TIM4_PWM_Pin);
//初始化TIM4
TIM_TimeBaseStructure.TIM_Period = arr - 1; //自动重装载值
TIM_TimeBaseStructure.TIM_Prescaler =psc - 1; //预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //
//初始化TIM4_CH2 PWM模式
TIM4_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //脉冲宽度调制模式2
TIM4_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM4_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性:TIM输出比较极性低
TIM_OC2Init(TIM4, &TIM4_OCInitStructure);
TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable); //使能TIM4在CCR2上的预装载寄存器
TIM_Cmd(TIM4, ENABLE); //使能TIM4
}
pwm.h
#ifndef __PWM_H
#define __PWM_H
文章来源:https://www.toymoban.com/news/detail-481239.html
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
void TIM4_PWM_Init(u16 arr,u16 psc); //初始化 定时器4_PWM
#endif
key.c
#include "key.h"
#include "delay.h"
void key_Config(void) //配置 主控按键
{
GPIO_InitTypeDef KEY_Pin;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
KEY_Pin.GPIO_Mode = GPIO_Mode_IPU; //上拉输入,按下0松开1
KEY_Pin.GPIO_Pin = GPIO_Pin_4;
KEY_Pin.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&KEY_Pin);
}
u8 KEY_Scan(u8 mode)//1连按,0单击
{
static u8 key_up=1;//按键按松开标志
if(mode)key_up=1;
if(key_up&&(KEY==0))
{
delay_ms(10);//去抖动
key_up=0;
if(KEY==0)return KEY_PRES;//1
}else if(KEY==1)key_up=1;
return 0;// 无按键按下
}
key.h
#ifndef __KEY_H
#define __KEY_H
#include "stm32f10x.h"
#include "delay.h"
#define KEY GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_4)
#define KEY_PRES 1 //按键按下
void key_Config(void); //配置按键
u8 KEY_Scan(u8 mode);
void key_function(void);
#endif
到了这里,关于stm32按键控制改变pwm占空比的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!