26. Chapter High-sensitivity microphone sensor

In this chapter, we will learn how to use High-sensitivity microphone sensor.

26.1. Project High-sensitivity microphone sensor and LED

This project will use a high-sensitivity microphone sensor to make a sound-controlled light.

26.1.1. Component List

  1. Raspberry Pi (with 40 GPIO) x1

  2. GPIO Extension Board & Ribbon Cable x1

  3. Breadboard x1

Jumper Wires x6

jumper-wire

High-sensitivity microphone sensor x1

microphone

LED x1

red-led

Resistor 220Ω x1

res-220R

26.1.2. Component knowledge

26.1.2.1. High-sensitivity microphone sensor

The high-sensitivity microphone sensor module is a component that accepts sound waves and converts them into electrical signals, which can detect the sound intensity in the surrounding environment.

When using it, it should be noted that this sensor can only identify the presence or absence of sound (according to the vibration principle), but cannot identify the size of the sound or the sound of a specific frequency.

This module has 4 pins: digital output (DO), analog output (AO), power supply positive pin and power supply negative pin. AO can output the voltage signal of the microphone in real time. When the ambient sound intensity does not reach the set threshold, the DO outputs a low-level signal, and when the ambient sound intensity exceeds the set threshold, it outputs a high-level signal, and the sensitivity can be adjusted by a potentiometer. When in use, adjust the potentiometer to make the sensitivity to sound reach a more appropriate value, and then read the digital output signal of the module through a pin on the development board. You can speak to the sensor. When the sensor detects a speaking sound, the DO pin outputs a high level; when the sensor does not detect a speaking sound, the DO pin outputs a low level.

Below is the pinout of the high-sensitivity microphone sensor.

Pin description:

symbol

Function

DO

Digital signal output

VCC

Power supply pin, +3.3V~5.0V

GND

GND

AO

Analog signal output

Since the default sensitivity of the high-sensitivity microphone sensor is high, the two LED lights on the module are lit up after power-on, and the sensitivity should be adjusted to an appropriate value at this time. When the potentiometer is adjusted clockwise, the module identification sensitivity increases; When counterclockwise adjustment potentiometer, module recognition sensitivity decreases. Please adjust the potentiometer before using the module to make its sensitivity reach the appropriate value. Under normal circumstances, you need counterclockwise rotation of the potentiometer, so that the output of the module LED off, when the sensitivity is low can be appropriate clockwise adjustment of the potentiometer, please ensure that your sensor output LED is extinguished when energized, in order to identify the sound.

Please do not use voltage beyond the power supply range to avoid damage to the high-sensitivity microphone sensor.

26.1.3. Circuit

Schematic diagram

microphone_Sc

Hardware connection. If you need any support,please feel free to contact us via:

support@freenove.com

microphone_Fr

26.1.4. Code

26.1.4.1. Python Code VoiceLamp

First observe the project result, and then learn about the code in detail.

Hint

If you have any concerns, please contact us via: support@freenove.com

  1. Use cd command to enter 26.1 1_VoiceLamp directory of Python code.

$ cd ~/Freenove_Kit/Code/Python_GPIOZero_Code/26.1.1_VoiceLamp
  1. Use python command to execute code VoiceLamp.py

$ python VoiceLamp.py

After the program is executed, when you speak to the sensor, the LED will turn on for 5 seconds. After 5 seconds, the LED will turn off. When the sensor does not recognize the sound, the LED will turn off.

The following is the program code:

 1#!/usr/bin/env python3
 2########################################################################
 3# Filename    : VoiceLamp.py
 4# Description : Make sound control lamp with high-sensitivity microphone sensor. 
 5# Author      : www.freenove.com
 6# modification: 2023/05/13
 7########################################################################
 8from gpiozero import LED
 9from sensor import MicrophoneSensor
10import time
11
12ledPin    = 17    # define ledPin
13sensorPin = 18    # define sensorPin
14led    = LED(ledPin)    
15sensor=MicrophoneSensor(sensorPin, pull_up=False)
16
17def loop():
18    while True:
19       if not sensor.is_active:
20           led.on()                    # turn on led
21           time.sleep(5)
22           led.off()                   # turn off led
23           print ('led turned on >>>') # print information on termina
24       else:
25           led.off()
26           print ('led turned off >>>')
27
28def destroy():
29    led.close() 
30    sensor.close()                     
31
32if __name__ == '__main__':     # Program entrance
33    print ('Program is starting...')
34    try:
35        loop()
36    except KeyboardInterrupt:  # Press ctrl-c to end the program.
37        destroy()
38        print("Ending program")

Import the MicrophoneSensor class from the sensor module. MicrophoneSensor is similar to the MotionSensor class in the GPIO Zero library in that they both actually use the SmoothedInputDevice class.

1from sensor import MicrophoneSensor

Read the signal pin of the high-sensitivity microphone sensor to determine whether the state of the sensor is high. When the sensor recognizes the sound, it outputs a high level, the variable sensor.is_active is True, and the LED will turn on for 5 seconds and then turn off.

 1def loop():
 2    while True:
 3       if not sensor.is_active:
 4           led.on()                    # turn on led
 5           time.sleep(5)
 6           led.off()                   # turn off led
 7           print ('led turned on >>>') # print information on termina
 8       else:
 9           led.off()
10           print ('led turned off >>>')

sensor.py

Import the SmoothedInputDevice class from the GPIO Zero library, create the MicrophoneSensor class, and initialize the parameters.

 1from gpiozero import SmoothedInputDevice
 2
 3class MicrophoneSensor(SmoothedInputDevice):
 4    def __init__(self, pin=None, *, pull_up=False, active_state=None,
 5                 queue_len=5, sample_rate=100, threshold=0.5, partial=False,
 6                 pin_factory=None):
 7        super().__init__(
 8            pin, pull_up=pull_up, active_state=active_state,
 9            threshold=threshold, queue_len=queue_len,
10            sample_wait=1 / sample_rate, partial=partial,
11            pin_factory=pin_factory)
12        self._queue.start()
13    @property
14    def value(self):
15        return super().value    
16    @property
17    def sound_detected(self):
18        return not self.is_active
19MicrophoneSensor.when_sound = MicrophoneSensor.when_deactivated
20MicrophoneSensor.when_no_sound = MicrophoneSensor.when_activated
21MicrophoneSensor.wait_for_sound = MicrophoneSensor.wait_for_inactive
22MicrophoneSensor.wait_for_no_sound = MicrophoneSensor.wait_for_active

See also

For more information about the methods used by the SmoothedInputDevice class in the GPIO Zero library,please refer to:

https://gpiozero.readthedocs.io/en/stable/api_input.html#smoothedinputdevice