pwm蜂鸣器、风扇、马达

pwm.h

 

#ifndef PWM_H__
#define PWM_H__
 
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_tim.h"
 
//蜂鸣器初始化
void hal_pwm_init();
//风扇初始化
void hal_fan_init();
//马达初始化
void hal_monitor_init();
 
 
#endif

 text.c

#include "pwm.h"
 
 
//蜂鸣器初始化  PB6--->TIM4_CH1
void hal_pwm_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 占空比	
	//分频器 
	TIM4->PSC &=(0xff);
	TIM4->PSC |=208;
	//自动重载计数器
	TIM4->ARR |=1000;
	//捕获/比较寄存器使能
	TIM4->CCER &=(~(0x1)<<3);
	TIM4->CCER |=(0x1<<1);
	TIM4->CCER |=(0x1);
	//初始化/使能捕获/比较寄存器
	TIM4->CCMR1 &=(~(0x1)<<16);
	TIM4->CCMR1 &=(~(0x7)<<4);
	TIM4->CCMR1 |=(0x3<<5);
	TIM4->CCMR1 |=(0x1<<3);
	//CCR
	TIM4->CCR1 |=300;
	//计数器
	TIM4->CR1 |=(0x1<<7);
	TIM4->CR1 &=(~(0x3<<5));
	TIM4->CR1 |=(0x1<<4);
	TIM4->CR1 &=(0x1);
}
//风扇初始化  	TIM1_CH1---->PE9
void hal_fan_init()
{
	//RCC章节初始化
	RCC->MP_AHB4ENSETR |=(0x1<<4);
	RCC->MP_APB2ENSETR |=(0x1);
	//GPIO章节初始化
	GPIOE->MODER &=(~(0X3<<18));
	GPIOE->MODER |=(0x1<<19);
	GPIOE->AFRH &=(0xf<<4);
	GPIOE->AFRH |=(0x1<<4);
	//TIM1章节
	TIM1->PSC &=(0xff);
	TIM1->PSC |=208;
	//ARR
	TIM1->ARR |=1000;
	//捕获/比较寄存器
	TIM1->CCER &=(~(0x1)<<3);
	TIM1->CCER |=(0x1<<1);
	TIM1->CCER |=0x1;
	//初始化捕获/比较寄存器
	TIM1->CCMR1 &=(~(0x1)<<16);
	TIM1->CCMR1 &=(~(0x7)<<4);
	TIM1->CCMR1 |=(0x3<<5);
	TIM1->CCMR1 |=(0x1<<3);
	//CCR
	TIM1->CCR1 |=300;
	//计数器
	TIM1->CR1 |=(0x1<<7);
	TIM1->CR1 &=(~(0x3<<5));
	TIM1->CR1 |=(0x1<<4);
	TIM1->CR1 &=(0x1);
	//BDTR
	TIM1->BDTR |=(0x1<<15);
}
//马达初始化  TIM16_CH1---->PF6
void hal_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);
	//TIM1章节
	TIM16->PSC &=(0xff);
	TIM16->PSC |=208;
	//ARR
	TIM16->ARR |=1000;
	//捕获/比较寄存器
	TIM16->CCER &=(~(0x1)<<3);
	TIM16->CCER |=(0x1<<1);
	TIM16->CCER |=0x1;
	//初始化捕获/比较寄存器
	TIM16->CCMR1 &=(~(0x1)<<16);
	TIM16->CCMR1 &=(~(0x7)<<4);
	TIM16->CCMR1 |=(0x3<<5);
	TIM16->CCMR1 |=(0x1<<3);
	//CCR
	TIM16->CCR1 |=300;
	//计数器
	TIM16->CR1 |=(0x1<<7);
	TIM16->CR1 &=(~(0x3<<5));
	TIM16->CR1 |=(0x1<<4);
	TIM16->CR1 &=(0x1);
	//BDTR
	TIM16->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 num[10]={0xFC,0x60,0xDA,0xF2,0x66,0xB6,0xBe,0xE0,0xFE,0xF6};
int main()
{
	hal_pwm_init(); 		//蜂鸣器初始化
	hal_fan_init(); 		//风扇初始化
	hal_monitor_init(); 	//马达初始化
	while(1)
	{
	}
	return 0;
}

你可能感兴趣的:(stm32,嵌入式硬件)