前言
今天记录的是声音传感器模块的学习

一、学习目的
我的学习目的是学会使用声音传感器模块,并通过检测声音的有无控制LED的亮灭。我使用的是STM32F103C8T6核心板上的自带LED,引脚是PC13。

二、模块介绍



我用的是上图所示的声音传感器,它只能通过震动判断声音的有无,而不能判断声音的大小和内容等。它和一般的传感器一样拥有四个引脚(AO,DO,GND,VCC)。
AO:模拟量输出,实时输出麦克风的电压信号。DO:当声音强度到达某个阈值时,输出高低电平信号[阈值灵敏度可以通过电位器调节]。
我们不需要太高精度的声音检测,只需要检测声音强度够大就可以实现声控灯的效果,所以我们只需要一个DO口就可以。

接线方面:GND—GND,VCC—5V,DO—PA11(可以自己更改引脚)

三、代码记录
voice.h (声音传感器的初始化)

#ifndef __VOICE_H
#define __VOICE_H


void VoiceSensor_Init(void);

uint8_t VoiceSensor_Get(void);

#endif

voice,c

当声音达到某个阈值,DO口输出高电平,对应的PA11口将呈现高电平状态,通过GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_11) 这个函数读取PA11的电平状态,从而控制LED。

#include "stm32f10x.h"                

void VoiceSensor_Init(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);


    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
}
//使能PA11口

uint8_t VoiceSensor_Get(void)     //读取PA11口的电平
{
    return GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_11);
}

bled.h (由DO口的高低电平检测控制LED的亮灭)

#ifndef __BLED_H
#define __BLED_H

void BLED_Init(void);
void BLED1_ON(void);
void BLED1_OFF(void);

void BLED1_Turn(void);

#endif

bled.c

#include "stm32f10x.h"               
#include "Delay.h"

void BLED_Init(void){
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);


    GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Pin=GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
    GPIO_Init(GPIOC,&GPIO_InitStructure);

    GPIO_SetBits(GPIOC,GPIO_Pin_13);
}

void BLED1_ON(void){               
    GPIO_ResetBits(GPIOC,GPIO_Pin_13);
}

void BLED1_OFF(void){
    GPIO_SetBits(GPIOC,GPIO_Pin_13);
}

void BLED1_Turn(void){
    if(GPIO_ReadOutputDataBit(GPIOC,GPIO_Pin_13)==0){
        GPIO_SetBits(GPIOC,GPIO_Pin_13);
    }else{
        GPIO_ResetBits(GPIOC,GPIO_Pin_13);
    }
}

main.c

通过读取PA11口的电平,判断是否有声音(有声音时为高电平)。

#include "stm32f10x.h"               
#include "Delay.h"
#include "bled.h"
#include "voice.h"

int main(void)
{
    BLED_Init();
    VoiceSensor_Init();

    while (1)
    {
        if (VoiceSensor_Get() == 1)     //如果PA11口为高电平,即有声音,灯亮
        {
            BLED1_ON();
        }
        else
        {
            BLED1_OFF();
        }
    }
}