STM32 study notes (four)

STM32F103ZET6 buzzer experiment



Preface

The learning of STM32 can be divided into 3 versions.
1. Register version
2. Library function version
3. HAL library version
Due to personal reasons, I choose the library function version to learn STM32.


Tip: Problems such as software installation will not be explained! ! !

1. Schematic

The schematic diagram shows that PB8 corresponds to BEEP.
Insert picture description here
Insert picture description here

Second, the program source code

1.beep.h

code show as below:

#ifndef _BEEP_H
#define _BEEP_H

void Beep_Init(void);

#endif

2.beep.c

code show as below:

#include "beep.h"
#include "stm32f10x.h"

void Beep_Init(void)
{
    
    
	GPIO_InitTypeDef GPIO_Initstr;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB , ENABLE);//时钟使能
	
	GPIO_Initstr.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_Initstr.GPIO_Pin=GPIO_Pin_8;
	GPIO_Initstr.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_Initstr);
	GPIO_ResetBits(GPIOB, GPIO_Pin_8);//初始化蜂鸣器关闭
}

3.main.c

code show as below:

#include "stm32f10x.h"
#include "led.h"
#include "delay.h"
#include "beep.h"

int main(void)
{
    
    
	delay_init();
    LED_Init();
	Beep_Init();
	while(1)
	{
    
    
		//库函数
		GPIO_ResetBits(GPIOB, GPIO_Pin_5);//LED1点亮,蜂鸣器不响
		GPIO_SetBits(GPIOE, GPIO_Pin_5);
		GPIO_ResetBits(GPIOB, GPIO_Pin_8);
		delay_ms(300);
		GPIO_SetBits(GPIOB, GPIO_Pin_5);//LED2点亮,蜂鸣器响
		GPIO_ResetBits(GPIOE, GPIO_Pin_5);
		GPIO_SetBits(GPIOB, GPIO_Pin_8);
		delay_ms(300);
		
		//位操作
//		PBout(5)=0;
//		PEout(5)=1;
//  	PBout(8)=0;
//  	delay_ms(300);
//  	PBout(5)=1;
//		PEout(5)=0;
//		PBout(8)=1;
//		delay_ms(300);
	}
}

3. Experimental results

When LED1 is on, the buzzer is off; when LED2 is on, the buzzer is on.


to sum up

Persistence is victory! ! !

The program implementation steps are as follows:
1. Clock enable
2. GPIO initialization
3. Control ODR register to output high and low levels

Guess you like

Origin blog.csdn.net/weixin_44935259/article/details/112494239