?PWM(蜂鸣器)框图
通过分析框图可知
1.分析RCC章节:相关控制器组使能
2.分析GPIO章节:复用模式/复用功能TIM4_CH1
3.分析TIM4章节:产生特定的方波?
?定时器工作原理
定时器工作原理:
1.当定时器启动之后,自动重载计数器中的值,会自动加载到递减计数器中
2.递减计数器在CK_CNT时钟驱动下进行工作
3.每来一个时钟周期,递减计数器中的值减1
4.当递减计数器中的值减到0的时候,自动重载计数器中的值,会再次自动加载到递减计数器中 --------------------如何产生PWM方波(比较/捕获寄存器)--------------------
1.当定时器启动之后,自动重载计数器中的值,会自动加载到递减计数器中
2.递减计数器在CK_CNT时钟驱动下进行工作
3.每来一个时钟周期,递减计数器中的值减1
4.如果减到和比较/捕获寄存器中的值相等之后,电平发生翻转,这样就可产生PWM方波信号
?pwm.h
#ifndef __PWM_H__
#define __PWM_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_tim.h"
//蜂鸣器初始化 pb6-tim4_ch1
void tim_init();
//马达初始化 pf6-tim16_ch1
void mada_init();
//风扇初始化 pe9-time1_ch1
void fan_init();
#endif
pwm.c
#include "pwm.h"
void tim_init()
{
//RCC_INIT
RCC->MP_AHB4ENSETR |= (0x1<<1);
RCC->MP_APB1ENSETR |= (0x1<<2);
//GPIO_INIT
GPIOB->MODER &= (~(0x3<<12));
GPIOB->MODER |= (0x2<<12);
GPIOB->AFRL &= (~(0xf<<24));
GPIOB->AFRL |= (0x2<<24);
//TIM_INIT
//设置分频器
TIM4->PSC = (208);
//设PWM方波占空比 对比较/捕获寄存器进行赋值
TIM4->CCR1 =(700);
//设置PWM方波最终周期
TIM4->ARR =(1000);
TIM4->CR1 |= (0x1<<7);
TIM4->CR1 &= (~(0x3<<5));
TIM4->CR1 |=(0x1<<4);
TIM4->CR1 |=(0x1<<0);
TIM4->CCMR1 &=(~(0x1<<16));
TIM4->CCMR1 &=(~(0x7<<4));
TIM4->CCMR1 |=(0x6<<4);
TIM4->CCMR1 |=(0x1<<3);
TIM4->CCMR1 &=(~(0x3<<0));
TIM4->CCER &=(~(0x1<<3));
TIM4->CCER &=(~(0x1<<1));
TIM4->CCER |=(0x1<<0);
}
//马达初始化 pf6-tim16_ch1
void mada_init()
{
RCC->MP_AHB4ENSETR |=0X1<<5;
RCC->MP_APB2ENSETR |=0X1<<3;
GPIOF->MODER &=(~(0X3<<12));
GPIOF->MODER |=(0X1<<13);
GPIOF->AFRL &=(~(0XF<<24));
GPIOF->AFRL |=0X1<<24;
//TIM_INIT
//设置分频器
TIM16->PSC = (208);
//设置PWM方波最终周期
TIM16->CCR1 =(700);
//设PWM方波占空比 对比较/捕获寄存器进行赋值
TIM16->ARR =(1000);
TIM16->CR1 |= (0x1<<7);
TIM16->CR1 &= (~(0x3<<5));
TIM16->CR1 |=(0x1<<4);
TIM16->CR1 |=(0x1<<0);
TIM16->CCMR1 &=(~(0x1<<16));
TIM16->CCMR1 &=(~(0x7<<4));
TIM16->CCMR1 |=(0x6<<4);
TIM16->CCMR1 |=(0x1<<3);
TIM16->CCMR1 &=(~(0x3<<0));
TIM16->CCER &=(~(0x1<<3));
TIM16->CCER &=(~(0x1<<1));
TIM16->CCER |=(0x1<<0);
TIM16->BDTR |=(0x1<<15);
}
//风扇初始化 pe9-time1_ch1
void fan_init()
{
RCC->MP_AHB4ENSETR |=0X1<<4;
RCC->MP_APB2ENSETR |=0X1<<0;
GPIOE->MODER &=(~(0X3<<18));
GPIOE->MODER |=(0X1<<19);
GPIOE->AFRH &=(~(0XF<<4));
GPIOE->AFRH |=0X1<<4;
//TIM_INIT
//设置分频器
TIM1->PSC = (208);
//设置PWM方波最终周期
TIM1->CCR1 =(700);
//设PWM方波占空比 对比较/捕获寄存器进行赋值
TIM1->ARR =(1000);
TIM1->CR1 |= (0x1<<7);
TIM1->CR1 &= (~(0x3<<5));
TIM1->CR1 |=(0x1<<4);
TIM1->CR1 |=(0x1<<0);
TIM1->CCMR1 &=(~(0x1<<16));
TIM1->CCMR1 &=(~(0x7<<4));
TIM1->CCMR1 |=(0x6<<4);
TIM1->CCMR1 |=(0x1<<3);
TIM1->CCMR1 &=(~(0x3<<0));
TIM1->CCER &=(~(0x1<<3));
TIM1->CCER &=(~(0x1<<1));
TIM1->CCER |=(0x1<<0);
TIM1->BDTR |=(0x1<<15);
}
main.c
#include "pwm.h"
extern void printf(const char *fmt, ...);
void delay_ms(int ms)
{
int i,j;
for(i = 0; i < ms;i++)
for (j = 0; j < 1800; j++);
}
int main()
{
tim_init();
mada_init();
fan_init();
while(1)
{
}
return 0;
}
|