创作本文目的:记录自己的学习历程
一、A7实现PWM器件启动的步骤
1.相关概念
1.PWM:脉冲宽度调制定时器 2.脉冲:方波信号,高低电平的变化产生方波信号 3.周期:高低电平变化所需要的时间,单位:ms 4.频率:周期和频率之间是倒数关系,1S钟可以产生的多少个方波信号,单位:HZ 5.占空比:高电平占整个周期的百分比 6.本次实验中:PWM/风扇/马达
2.分析硬件
蜂鸣器:TIM4_CH1----> PB6 gpio toggle gpiob6 风扇:TIM1_CH1----> PE9 gpiotoggle gpioe9 马达:TIM16_CH1----> PF6 gpio toggle gpiof6
3.分析芯片手册
分析RCC章节:相关控制器组使能 分析GPIO章节:复用模式/复用功能 分析TIM章节:产生特定的方波
3.1 RCC时钟使能
GPIOB组和TIM4组时钟使能---蜂鸣器
GPIOF组和TIM16组时钟使能---马达
GPIOE组,TIM1组时钟使能---风扇
3.2 GPIO复用功能
MODER寄存器
AFRL/AFRH寄存器
3.3 TIM*产生方波
BDTR(风扇和马达需要)
CCR1 --- 影响PWM方波占空比
ARR --- 影响PWM方波的周期和频率
PSC --- 设置预分频器
CCER --- 设置输出PWM方波的极性
CCMR1 --- 设置指定通道为PWM1模式 和 输出捕获预加载使能
CR1 --- 配置tim计数器方式(自动重载计数器预加载使能,设置边沿对齐模式,设置递减计数器,设置计数器使能)
4.PWM方波的产生
1.当定时器启动之后,自动重载计数器中的值,会自动加载到递减计数器中 2.递减计数器在CK_CNT时钟驱动下进行工作 3.每来一个时钟周期,递减计数器中的值减1 4.如果减到和比较/捕获寄存器中的值相等之后,电平发生翻转,这样就可产生PWM方波信号
5.部分程序
#include "beep.h"
void my_fan_tim1_init()
{
RCC->MP_AHB4ENSETR |= (0x1 << 4);
RCC->MP_APB2ENSETR |= (0x1 << 0);
GPIOE->MODER &= (~(0x3 << 18));
GPIOE->MODER |= (0x2 << 18);
GPIOE->AFRH &= (~(0xF << 4));
GPIOE->AFRH |= (0x1 << 4);
TIM1->BDTR |= (0x1 << 15);
TIM1->PSC = 209 - 1;
TIM1->ARR = 10000;
TIM1->CCR1 = 5000;
TIM1->CCMR1 &= (~(0x1 << 16));
TIM1->CCMR1 &= (~(0x7 << 4));
TIM1->CCMR1 |= (0x6 << 4);
TIM1->CCMR1 &= (~(0x3 << 0));
TIM1->CCMR1 |= (0x1 << 3);
TIM1->CCER &= (~(0x1 << 3));
TIM1->CCER &= ~(0x1 << 1);
TIM1->CCER |= (0x1 << 0);
TIM1->CR1 |= (0x1 << 7);
TIM1->CR1 &= (~(0x3 << 5));
TIM1->CR1 |= (0x1 << 4);
TIM1->CR1 |= (0x1 << 0);
}
void my_motor_tim16_init()
{
RCC->MP_AHB4ENSETR |= (0x1 << 5);
RCC->MP_APB2ENSETR |= (0x1 << 3);
GPIOF->MODER &= (~(0x3 << 12));
GPIOF->MODER |= (0x2 << 12);
GPIOF->AFRL &= (~(0xF << 24));
GPIOF->AFRL |= (0x1 << 24);
TIM16->BDTR |= (0x1 << 15);
TIM16->PSC = 209 - 1;
TIM16->ARR = 1000;
TIM16->CCR1 = 300;
TIM16->CCMR1 &= (~(0x1 << 16));
TIM16->CCMR1 &= (~(0x7 << 4));
TIM16->CCMR1 |= (0x6 << 4);
TIM16->CCMR1 &= (~(0x3 << 0));
TIM16->CCMR1 |= (0x1 << 3);
TIM16->CCER &= (~(0x1 << 3));
TIM16->CCER &= ~(0x1 << 1);
TIM16->CCER |= (0x1 << 0);
TIM16->CR1 |= (0x1 << 7);
TIM16->CR1 |= (0x1 << 0);
}
void my_beep_tim4_init()
{
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_APB1ENSETR |= (0x1 << 2);
GPIOB->MODER &= (~(0x3 << 12));
GPIOB->MODER |= (0x1 << 13);
GPIOB->AFRL &= (~(0xf <<24));
GPIOB->AFRL |= (0x1 << 25);
TIM4->CR1 &= (~(0xf << 4));
TIM4->CR1 |= (0x9 << 4);
TIM4->CR1 |= 0x1;
TIM4->CCMR1 &= (~(0x1 << 16));
TIM4->CCMR1 &= (~(0x7 << 4));
TIM4->CCMR1 |= (0x3 << 3);
TIM4->CCMR1 |= (0x1 << 3);
TIM4->CCMR1 &= (~(0x3 << 0));
TIM4->CCER |= (0x1 << 3);
TIM4->CCER &= (~(0x3 << 0));
TIM4->CCER |= (0x1 << 0);
TIM4->PSC &= (~(0x0 << 15));
TIM4->PSC |= 0xD0;
TIM4->ARR &= (~(0x0 << 31));
TIM4->ARR |= 0x3E8;
TIM4->CCR1 &=(~(0x0 << 31));
TIM4->CCR1 |= 0x12C;
}
在主函数调用即可
6.效果
|