Controlling an LED With a Snap Using the KY-037 Sound Sensor and Raspberry Pi

by mahmoodmustafashilleh in Circuits > Raspberry Pi

66 Views, 2 Favorites, 0 Comments

Controlling an LED With a Snap Using the KY-037 Sound Sensor and Raspberry Pi

KY037 P2 Square.png

Welcome back to part 2 of our KY-037 sound sensor tutorial series! In part 1, we successfully set up the KY-037 sound sensor with a Raspberry Pi to detect sound using its digital output. If you haven’t gone through that tutorial yet, I recommend starting there, as this guide builds upon the previous one.

In this tutorial, we’ll go a step further by integrating an LED that turns on and off based on sound detection. With just a snap of your fingers or a clap, the LED will react accordingly. This project is a fun and interactive way to learn how to control physical components with sound, making it perfect for beginner IoT enthusiasts.

— — -

Before we delve into the topic, we invite you to support our ongoing efforts and explore our various platforms dedicated to enhancing your IoT projects:

  1. Subscribe to our YouTube Channel: Stay updated with our latest tutorials and project insights by subscribing to our channel at YouTube — Shilleh.
  2. Support Us: Your support is invaluable. Consider buying me a coffee at Buy Me A Coffee to help us continue creating quality content.
  3. Hire Expert IoT Services: For personalized assistance with your IoT projects, hire me on UpWork.

ShillehTek Website (Exclusive Discounts):

https://shillehtek.com/collections/all

ShillehTekAmazon Store:

ShillehTek Amazon Store — US

ShillehTek Amazon Store — Canada

ShillehTek Amazon Store — Japan

Supplies

To get started, you’ll need the following components:

  1. KY-037 Sound Sensor: Available at ShillehTek Amazon Store.
  2. Raspberry Pi (any model with GPIO pins): I’m using a Raspberry Pi 4B.
  3. 3 Male-to-Female Jumper Wires: For connecting the sensor to the Raspberry Pi.
  4. 1 LED: Any color will work, but I’ll be using a red LED.
  5. 1 220-ohm Resistor: To prevent the LED from drawing too much current.
  6. Breadboard (optional): For organizing your connections.
  7. A thin screwdriver: For adjusting the potentiometer on the KY-037 sensor.

Wiring the KY-037 Sound Sensor and LED to the Raspberry Pi

Before we dive into the wiring, let’s first understand our setup. The sound sensor will detect a snap or clap and send a digital signal to the Raspberry Pi. The Pi will then process this signal and decide whether to turn the LED on or off.

Here’s how you’ll wire the components:

Wiring the KY-037 Sound Sensor:

  1. VCC (Power) pin of the KY-037 connects to pin 2 (5V) on the Raspberry Pi.
  2. GND (Ground) pin of the KY-037 connects to pin 6 (Ground) on the Raspberry Pi.
  3. D0 (Digital Output) pin of the KY-037 connects to GPIO 4 on the Raspberry Pi (pin 7 in physical pin layout).

Wiring the LED:

  1. Connect the longer leg (positive) of the LED to GPIO 17 on the Raspberry Pi (pin 11 in physical layout).
  2. Connect the shorter leg (negative) of the LED to one end of the 220-ohm resistor.
  3. Connect the other end of the resistor to GND on the Raspberry Pi (pin 9 in physical layout).

Your setup should look something like this:

KY-037 to Raspberry Pi:

  1. VCC -> 5V (Pin 2)
  2. GND -> GND (Pin 6)
  3. D0 -> GPIO 4 (Pin 7)

LED to Raspberry Pi:

  1. Long Leg (Anode) -> GPIO 17 (Pin 11)
  2. Short Leg (Cathode) -> 220-ohm Resistor -> GND (Pin 9)
  3. In summary, the GPIO pin acts as a power source when set to High, allowing the LED to be powered and controlled through software.

Important Note: Make sure to connect the resistor to prevent too much current from flowing through the LED, which could damage it.

As I mentioned in Part 1, you should fine-tune the potentiometer to the point just below the detection threshold, allowing a snap to easily push it past the limit and trigger a response.

Here is how it looks in real life:


Writing the Python Code

Now that we have our components connected, let’s write the Python script to control the LED based on sound detection.

Create a new Python file called sound_led_control.py on your Raspberry Pi and add the following code:

import RPi.GPIO as GPIO
import time

# Set up GPIO pin numbering mode and define pins for sensor and LED
GPIO.setmode(GPIO.BCM)
SOUND_SENSOR_PIN = 4 # GPIO pin number connected to D0 pin of KY-037
LED_PIN = 17 # GPIO pin number connected to LED

# Set up the pins
GPIO.setup(SOUND_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Configure sound sensor pin as input
GPIO.setup(LED_PIN, GPIO.OUT) # Configure LED pin as output

# Initialize LED state
led_state = False

# Function to toggle LED based on sound detection
def toggle_led():
global led_state
if led_state:
GPIO.output(LED_PIN, GPIO.LOW) # Turn off the LED
print("LED turned OFF")
else:
GPIO.output(LED_PIN, GPIO.HIGH) # Turn on the LED
print("LED turned ON")
led_state = not led_state # Toggle the state

# Main loop to check for sound detection and toggle LED
try:
print("Starting sound sensor program. Snap or clap to toggle the LED.")
while True:
if GPIO.input(SOUND_SENSOR_PIN) == 1: # Sound detected
toggle_led()
time.sleep(1) # Wait for a second to avoid multiple toggles on one sound
except KeyboardInterrupt:
print("Program interrupted. Cleaning up GPIO settings.")
finally:
GPIO.cleanup() # Clean up all GPIO settings

Explanation of the Code:

  1. Setup: We configure the sound sensor pin as an input and the LED pin as an output.
  2. Global LED State: We keep track of whether the LED is on or off using the led_state variable.
  3. toggle_led() Function: This function toggles the LED based on its current state.
  4. Main Loop: The loop continuously checks for sound detection. If a sound is detected, it calls toggle_led() and then waits for 1 second to avoid rapid toggling.

Running the Code

Once you’ve copied the code into sound_led_control.py, it’s time to run it! Open a terminal on your Raspberry Pi and navigate to the directory where the file is located. Then, run:

python3 sound_led_control.py

You should see a message in the terminal saying, “Starting sound sensor program. Snap or clap to toggle the LED.”

Testing: Try snapping your fingers or clapping near the sensor. The LED should turn on or off with each snap or clap, depending on its current state. If the LED isn’t responding as expected, adjust the potentiometer on the KY-037 to fine-tune its sensitivity.

Conclusion and What’s Next?

Congratulations! You’ve successfully created a sound-activated LED control system using the KY-037 sound sensor and Raspberry Pi. In this tutorial, we learned:

  1. How to wire the KY-037 sound sensor and an LED to the Raspberry Pi.
  2. How to write a Python script to toggle the LED based on sound detection.

This project can serve as the foundation for more advanced sound-activated systems, such as creating a sound-responsive smart home lighting system or building an interactive sound-based game.

In the next tutorial, we’ll explore connecting multiple sound sensors to create more complex systems or use the analog output of the KY-037 for measuring sound intensity. Until then, keep experimenting and learning!

Support and Resources:

  1. Don’t forget to check out my YouTube Channel for more tutorials.
  2. Consider supporting me on Buy Me a Coffee to help fund future content creation.
  3. For custom projects or professional consulting, feel free to hire me on Upwork.

Happy coding, and see you in the next tutorial!