蜂鸣器实验
硬件连接
用一个 NPN 三极管(S8050)来驱动蜂鸣器,R61 主要用于防止蜂鸣器的误发声。当 PF8 输出高电平的时候,蜂鸣器将发声,当 PF8 输出低电平的时候,蜂鸣器停止发声。
编写程序
蜂鸣器实验也是GPIO的输出实验和上一篇的笔记都差不多,首先要先写beep.h和beep.c中的程序。
beep.h :
#ifndef BEEP_H
#define BEEP_H
void BEEP_Init(void);
#endif
beep.c :
#include "stm32f4xx.h"
#include "beep.h"
void BEEP_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType=GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_8|GPIO_Pin_9;//为了操作led所以也初始化了PF9
GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_100MHz;
GPIO_Init(GPIOF,&GPIO_InitStruct);
GPIO_ResetBits(GPIOF,GPIO_Pin_8);
GPIO_SetBits(GPIOF,GPIO_Pin_9);
}
编写main.c中的代码使led亮点时候蜂鸣器响
#include "beep.h"
#include "delay.h"
#include "stm32f4xx.h"
int main(void)
{
delay_init(168);
BEEP_Init();
while(1)
{
PFout(8)=0;
PFout(9)=1;
delay_ms(500);
PFout(8)=1;
PFout(9)=0;
delay_ms(500);
}
}
运行效果:
BEEP
按键输入实验
硬件连接
因为当按下KEY_UP时会输入高电压所以在设置上下拉时应设置下拉使其未按下按键时为低电压,KEY0,1,2则与之相反。
编写代码
初始化代码和上面类似,但会多加一个读取按键输入函数。
key.h :
#ifndef KEY_H
#define KEY_H
void KEY_Init(void);
int KEY_Scan(int mode);
#endif
key.c 中初始化函数:
#include "stm32f4xx.h"
#include "key.h"
#include "delay.h"
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOE, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOE, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
按键的输入有两种模式,长时间按读取一次,长时间按读取多次,下面是读取按键输入函数:
int KEY_Scan(int mode)//输入参数1支持连续按,0不支持连续按
{
static int key_up=1;
if(mode)
key_up=1;
if(key_up&&(PAin(0)==1||PEin(2)==0||PEin(3)==0||PEin(4)==0))
{
delay_ms(10);//防抖
key_up=0;
if(PAin(0)==1)
return 1;
else if(PEin(2)==0)
return 2;
else if(PEin(3)==0)
return 3;
else if(PEin(4)==0)
return 4;
}
else if((PAin(0)==0&&PEin(2)==1&&PEin(3)==1&&PEin(4)==1))
key_up=1;
return 0;
}
接下来是main.c中的代码,设计为按下KEY2红led灯转换状态,按下KEY1绿led灯转换状态,按下KEY0两个led灯都转化状态,按下KEY_UP蜂鸣器响一下。
#include "stm32f4xx.h"
#include "led.h"
#include "beep.h"
#include "delay.h"
#include "key.h"
int main(void)
{
delay_init(168);
LED_Init();
BEEP_Init();
KEY_Init();
PFout(9)=0;
while(1)
{
int key=KEY_Scan(0);
if(key)
switch(key)
{
case 1:
PFout(8)=1;
delay_ms(300);
PFout(8)=0;
break;
case 2:
PFout(9)=!PFout(9);
PFout(10)=!PFout(10);
break;
case 3:
PFout(10)=!PFout(10);
break;
case 4:
PFout(9)=!PFout(9);
break;
}
}
}
运行结果:
按键