作业需求:编写蜂鸣器/风扇/马达代码
实现过程:
#ifndef __PWM_H__
#define __PWM_H__
#include"stm32mp1xx_tim.h"
#include"stm32mp1xx_rcc.h"
#include"stm32mp1xx_gpio.h"
//蜂鸣器初始化
void beep_init();
//风扇初始化
void fan_init();
//马达初始化
void monitor_init();
#endif
源文件:
#include "pwm.h"
//蜂鸣器初始化
void beep_init()
{
/*****RCC章节****/
RCC->MP_AHB4ENSETR |= (0x1<<1);
RCC->MP_APB1ENSETR |=(0x1<<2);
/*****GPIO章节****/
GPIOB->MODER &= (~(0x3<<12));
GPIOB->MODER |= (0x1<<13);
GPIOB->AFRL &= (~(0xf<<24));
GPIOB->AFRL |=(0x1<<25);
/****TIM4章节 1000HZ~2000HZ*****/
TIM4->CR1 |=(0x1<<7);
TIM4->CR1 &=(~(0x3<<5));
TIM4->CR1 |=(0x1<<4);
TIM4->CR1 |=(0x1);
TIM4->CCMR1 &=(~(0x1<<16));
TIM4->CCMR1 &=(~(0x7<<4));
TIM4->CCMR1 |=(0x3<<5);
TIM4->CCMR1 |=(0x1<<3);
TIM4->CCMR1 &=(~(0x3));
TIM4->CCER &=(~(0x1<<3));
TIM4->CCER |=(0x1<<1);
TIM4->CCER |=(0x1);
TIM4->PSC |=0xD0;
TIM4->ARR |=0x3E8;
TIM4->CCR1 =700;
}
//风扇初始化
void fan_init()
{
/*****RCC章节****/
RCC->MP_AHB4ENSETR |=(0x1<<4);//GPIOE组使能
RCC->MP_APB2ENSETR |=(0x1); //TIM1使能
/*****GPIO章节****/
GPIOE->MODER &= (~(0x3<<18));//设置GPIOE复用模式
GPIOE->MODER |= (0x1<<19);
GPIOE->AFRH &= (~(0xf<<4));//设置pe9为TIM_ch1
GPIOE->AFRH |=(0x1<<4);
/****TIM1章节 1000HZ~2000HZ*****/
TIM1->CR1 |=(0x1<<7);//自动重载预加载函数
TIM1->CR1 &=(~(0x3<<5));//边沿对齐
TIM1->CR1 |=(0x1<<4);//采用递减方式进行计数
TIM1->CR1 |=(0x1);//计算器使能
TIM1->CCMR1 &=(~(0x1<<16));//设置输出模式为PWM模式
TIM1->CCMR1 &=(~(0x7<<4));
TIM1->CCMR1 |=(0x3<<5);
TIM1->CCMR1 |=(0x1<<3);//设置输出比较寄存器
TIM1->CCMR1 &=(~(0x3));//设置通道为输出模式
TIM1->CCER &=(~(0x1<<3));//配置通道1为输出极性模式
TIM1->CCER &=(~(0x1<<1));//设置起始电平
TIM1->CCER |=(0x1);//配置通道1输出使能
TIM1->PSC |=0xD0;//设分频
TIM1->ARR |=0x3E8;//设置自动重载寄存器
TIM1->CCR1 =700;//设置比较捕获寄存器
TIM1->BDTR |=(0x1<<15);
}
//马达初始化
void monitor_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);
TIM16->CR1 |=(0x1<<7);
TIM16->CR1 &=(~(0x3<<5));
TIM16->CR1 |=(0x1<<4);
TIM16->CR1 |=(0x1);
TIM16->CCMR1 &=(~(0x1<<16));
TIM16->CCMR1 &=(~(0x7<<4));
TIM16->CCMR1 |=(0x3<<5);
TIM16->CCMR1 |=(0x1<<3);
TIM16->CCMR1 &=(~(0x3));
TIM16->CCER &=(~(0x1<<3));
TIM16->CCER |=(0x1<<1);
TIM16->CCER |=(0x1);
TIM16->PSC |=0xD0;
TIM16->ARR |=0x3E8;
TIM16->CCR1 =700;
TIM16->BDTR |= (0x1<<15);
}
测试文件:
#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()
{
//beep_init();
fan_init();
//monitor_init();
while(1)
{
}
return 0;
}