作业:
编写蜂鸣器/风扇/马达代码
头文件:
#ifndef __PWM_H__
#define __PWM_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_tim.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);
//TIME初始化
//分频器寄存器
TIM4->PSC &= (~(0xffff));
TIM4->PSC |= (0xd0);
//自动重载计数器配置1000
TIM4->ARR &= (~(0xffff));
TIM4->ARR |= (0x3e8);
//初始化计数器
TIM4->CR1 |= (0x1<<7);
TIM4->CR1 |= (0x1<<4);
TIM4->CR1 |= (0x1<<0);
TIM4->CR1 &= (~(0x3<<5));
//设置TIM4_CH1通道模式寄存器
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);
//捕获比较寄存器配置
TIM4->CCR1 &= (~(0xffff<<0));
TIM4->CCR1 |= (0x2bc<<0);
}
//风扇初始化
void fan_init()
{
//PE9、TIME1
//RCC初始化
RCC->MP_AHB4ENSETR |= (0x1<<4);
RCC->MP_APB2ENSETR |= (0x1<<0);
//GPIO初始化
GPIOE->MODER &= (~(0x3<<18));
GPIOE->MODER |= (0x1<<19);
GPIOE->AFRH &= (~(0xf<<4));
GPIOE->AFRH |= (0x1<<4);
//TIME初始化
//分频器寄存器
TIM1->PSC &= (~(0xffff));
TIM1->PSC |= (0xd0);
//自动重载计数器配置1000
TIM1->ARR &= (~(0xffff));
TIM1->ARR |= (0x3e8);
//初始化计数器
TIM1->CR1 |= (0x1<<7);
TIM1->CR1 |= (0x1<<4);
TIM1->CR1 |= (0x1<<0);
TIM1->CR1 &= (~(0x3<<5));
//设置TIM1_CH1通道模式寄存器
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->CCR1 &= (~(0xffff<<0));
TIM1->CCR1 |= (0x2bc<<0);
TIM1->BDTR |= (0x1<<15);
}
//马达初始化
void monitor_init()
{
//RCC初始化
RCC->MP_AHB4ENSETR |= (0x1<<5);
RCC->MP_APB2ENSETR |= (0x1<<3);
//GPIO初始化
GPIOF->MODER &= (~(0x3<<12));
GPIOF->MODER |= (0x1<<13);
GPIOF->AFRL &= (~(0xf<<24));
GPIOF->AFRL |= (0x1<<24);
//TIME初始化
//分频器寄存器
TIM16->PSC &= (~(0xffff));
TIM16->PSC |= (0xd0);
//自动重载计数器配置1000
TIM16->ARR &= (~(0xffff));
TIM16->ARR |= (0x3e8);
//初始化计数器
TIM16->CR1 |= (0x1<<7);
TIM16->CR1 |= (0x1<<4);
TIM16->CR1 |= (0x1<<0);
TIM16->CR1 &= (~(0x3<<5));
//设置TIM16_CH1通道模式寄存器
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->CCR1 &= (~(0xffff<<0));
TIM16->CCR1 |= (0x2bc<<0);
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;
}