PWM实现蜂鸣器

2023-12-15 18:35:14

tim4.h

#ifndef __TIM4_H__
#define __TIM4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_tim.h"
void timer4_init();

#endif

tim4.c

#include "tim4.h"


void timer4_init()
{
    // 1. 设置GPIOB,TIM4的时钟使能   RCC_MP_AHB4ENSETR  RCC_MP_APB1ENSETR
    RCC->MP_AHB4ENSETR |= (0x1 << 1);
    RCC->MP_APB1ENSETR |= (0x1 << 2);
    // 2. 设置PB6引脚为复用功能       GPIOB_MODER
    GPIOB->MODER &= (~(0x3 << 12));
    GPIOB->MODER |= (0x2 << 12);
    // 3. 设置PB6引脚为TIM4_CH1功能   GPIOB_AFRL
    GPIOB->AFRL &= (~(0xF << 24));
    GPIOB->AFRL |= (0x2 << 24);
    // 4. 设置预分频寄存器,TIM4_PSC[15:0]  CK_PSC = 209MHz  
    //      提供给TIM4的时钟源的频率是209MHz
    TIM4->PSC = 20900-1;    
    // 5. 设置PWM方波的最终的周期  TIM4_ARR[15:0]  自动装载寄存器
    //      得到一个1000-2000Hz的方波
    TIM4->ARR =10000;
    // 5. 设置PWM方波的占空比   TIM4_CCR1[15:0]  比较寄存器
    TIM4->CCR1 = 7000;
    // 6. 设置TIM4_CH1通道为PWM1模式  
    //      TIM4_CCMR1[16]  TIM4_CCMR1[6:4]  pwm模式1  = 0b0110
    TIM4->CCMR1 &= (~(0x1 << 16));
    TIM4->CCMR1 &= (~(0x7 << 4));
    TIM4->CCMR1 |= (0x6 << 4);
    // 7. 设置TIM4_CH1通道使能TIMx_CCR1预加载使能寄存器  比较寄存器使能
    //      TIM4_CCMR1[3] = 0x1
    TIM4->CCMR1 |= (0x1 << 3);
    // 8. 设置TIM4_CH1通道输出PWM方波的极性,
    //    TIM_CCER[3] = 0b0 TIM4_CCER[1] = 0x1 or 0x0
    TIM4->CCER &= (~(0x1 << 3));
    TIM4->CCER |= (0x1 << 1);
    //TIM4->CCER &= (~(0x1 << 1));
    
    // 9. 设置TIM4_CH1通道的输出使能位,输出PWM方波 
    //      TIM4_CCER[0] = 0x1
    TIM4->CCER |= (0x1 << 0);
    // 10. 设置TIM4_CH1通道的预装载寄存器的缓冲区的使能
    //      TIM4_CR1[7] = 0x1
    TIM4->CR1 |= (0x1 << 7);
    // 11. 设置定时器的计数方式,边沿对齐
    //      TIM4_CR1[6:5] = 0x0
    TIM4->CR1 &= (~(0x3 << 5));
    // 12 设置定时器计数的方向,采用递减计数/递增计数 
    //      TIM4_CR1[4] = 0x1 
    TIM4->CR1 |= (0x1 << 4);
    // 13. 使能TIM4_CH1计数器 
    //      TIM4_CR1[0] = 0x1
    TIM4->CR1 |= (0x1 << 0);
}

main.c

#include "tim4.h"



void delay(int ms)

{

  int i,j;

  for(i=0;i<ms;i++)

  {

  for(j=0;j<2000;j++);

  }

}



int num[10] = {0xFC,0x60,0xDA,0xF2,0x66,0xB6,0x3E,0xE0,0xFE,0xF6};

int main()

{

    timer4_init();

    while(1)

    {

        

    }//保证程序不结束



    return 0;

}

文章来源:https://blog.csdn.net/m0_67896905/article/details/135021143
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。