Overview

The KY-037 sound sensor module allows your Vumbua Synapse Kit to "hear" the world around it. Unlike microphones that capture audio for playback, sound sensors detect the presence and intensity of sound, making them perfect for sound-activated switches, noise monitoring systems, and clap-controlled devices.

In this lesson, you'll learn how to interface the KY-037 sound sensor with your Vumbua Synapse Kit. The sensor's analog output is connected to pin A1 on the Vumbua board, allowing you to measure sound intensity levels with precision.

Real-World Applications

Sound sensors are used in:

  • Clap-controlled lights and appliances
  • Noise monitoring in offices and libraries
  • Security systems for glass break detection
  • Voice-activated devices and toys
  • Industrial noise level monitoring
  • Interactive art installations

Prerequisites

Before starting, make sure you have completed:

Completed Lessons
  • Lesson 1: Blinking LED
  • Lesson 3: Buzzer Sound Generation
  • Lesson 4: Potentiometer (Analog Input)
  • Understanding of analogRead() function
  • Basic knowledge of sound wave properties
Hardware Requirements
  • Vumbua Synapse Kit with KY-037 sound sensor
  • USB Type-C cable
  • Computer with Arduino IDE
  • Quiet and noisy environments for testing
KY-037 Sensor Features

The KY-037 sound sensor on the Vumbua Synapse Kit has:

  • High sensitivity microphone
  • Adjustable sensitivity potentiometer (blue knob)
  • Both digital (DO) and analog (AO) outputs
  • Built-in LM393 comparator chip
  • LED indicator for digital output status

Learning Objectives

By the end of this lesson, you will be able to:

  • Understand how sound sensor modules work
  • Connect the KY-037 sensor to Vumbua (AO=A1)
  • Read analog sound intensity values with analogRead()
  • Calibrate sensor sensitivity using the potentiometer
  • Detect sound events and set appropriate thresholds
  • Create a clap detection system with timing logic
  • Build a sound level meter with visual feedback
  • Understand the physics of sound wave detection
  • Troubleshoot common sound sensor issues

What is a Sound Sensor?

Understanding Sound Waves

Sound is a mechanical wave that travels through air (or other mediums) as pressure variations. The KY-037 sensor detects these pressure changes using an electret microphone, which converts sound waves into electrical signals.

Sound intensity is measured in decibels (dB), but our sensor provides relative intensity values (0-1023 on the analog pin).

KY-037 Module Components

The KY-037 module contains several key components:

  1. Electret Microphone: Captures sound waves
  2. LM393 Comparator: Compares signal to threshold
  3. Sensitivity Potentiometer: Adjusts detection threshold
  4. Analog Output (AO): Raw microphone signal (connected to A1)
  5. Digital Output (DO): HIGH/LOW based on threshold
  6. LED Indicator: Lights when DO is HIGH
How It Works

When sound waves hit the microphone, they create varying electrical signals. These signals are amplified and:

  • On AO pin: You get the raw analog value (0-1023)
  • On DO pin: You get HIGH if sound exceeds threshold, LOW otherwise

For the Vumbua Kit, we use the AO pin connected to A1 for precise sound level measurement.

Sensor Pin Connections

The KY-037 sound sensor has 4 pins that connect to the Vumbua Synapse Kit:

VCC
Power Supply (5V)
5V on Vumbua
GND
Ground (0V)
GND on Vumbua
AO (Analog Output)
Analog sound signal output
Analog Pin A1
DO (Digital Output)
Digital HIGH/LOW output
Not Connected (Analog Only)
Important: On Vumbua Synapse Kit

The KY-037 sound sensor is already pre-connected to the Vumbua board:

  • AO (Analog Output): Connected to A1 (Analog Pin 1)
  • VCC: Connected to 5V
  • GND: Connected to GND
  • DO (Digital Output): Not connected (we use analog only)

You don't need to make any physical connections - just write the code!

Sensitivity Adjustment

The blue potentiometer on the KY-037 module adjusts the sensitivity:

  • Clockwise: Increases sensitivity (detects quieter sounds)
  • Counter-clockwise: Decreases sensitivity (requires louder sounds)

For most applications, start with the potentiometer in the middle position, then adjust based on your environment.

Analog vs Digital Output

The KY-037 provides two types of outputs - understanding the difference is crucial:

Analog Output (AO)

Connected to A1 on Vumbua

  • Provides raw sound intensity (0-1023)
  • Values change smoothly with sound level
  • Allows precise measurement
  • Can detect volume differences
  • Use with analogRead(A1)

Best for: Sound level meters, noise monitoring

Digital Output (DO)

Not connected on Vumbua

  • Provides HIGH/LOW signal only
  • HIGH when sound exceeds threshold
  • LOW when sound is below threshold
  • Threshold set by potentiometer
  • LED lights when HIGH

Best for: Simple sound detection, on/off switches

Why Use Analog Output?

On the Vumbua Synapse Kit, we use the analog output (A1) instead of digital because:

  • Provides more information (not just on/off)
  • Allows us to set software thresholds
  • Can measure sound intensity changes
  • More flexible for different applications
  • Better for learning sound sensor principles

Basic Sound Detection

Let's start with a simple program to read sound levels from the sensor:

sound_basic.ino
/*
  Vumbua Synapse Kit - Lesson 7: Basic Sound Sensor
  Read sound levels from KY-037 sensor on pin A1
*/

// KY-037 Sound Sensor connected to A1
const int soundSensorPin = A1;
const int ledPin = 13;  // Built-in LED

// Variables for sound measurement
int soundValue = 0;        // Raw analog reading (0-1023)
int soundLevel = 0;        // Normalized level (0-100)
int baseline = 0;          // Ambient noise baseline
int samples = 50;          // Number of samples for averaging

void setup() {
  // Initialize Serial communication
  Serial.begin(9600);
  
  // Configure LED pin
  pinMode(ledPin, OUTPUT);
  
  // Note: soundSensorPin is analog, no pinMode needed
  
  Serial.println("Vumbua Sound Sensor - Basic Detection");
  Serial.println("======================================");
  
  // Calibrate baseline (ambient noise level)
  calibrateBaseline();
  
  Serial.print("Baseline noise level: ");
  Serial.println(baseline);
  Serial.println("Ready to detect sounds!");
  Serial.println();
}

void loop() {
  // Read sound sensor value
  soundValue = analogRead(soundSensorPin);
  
  // Calculate sound level relative to baseline (0-100 scale)
  soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Display raw and processed values
  Serial.print("Raw: ");
  Serial.print(soundValue);
  Serial.print("  |  Level: ");
  Serial.print(soundLevel);
  Serial.print("%  |  ");
  
  // Visual feedback with LED
  if (soundLevel > 30) {
    Serial.println("LOUD!");
    digitalWrite(ledPin, HIGH);
  } else if (soundLevel > 10) {
    Serial.println("Medium");
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    delay(100);
  } else {
    Serial.println("Quiet");
    digitalWrite(ledPin, LOW);
  }
  
  // Small delay between readings
  delay(50);
}

// Function to calibrate ambient noise baseline
void calibrateBaseline() {
  Serial.println("Calibrating... Please be quiet for 3 seconds.");
  delay(1000);
  
  long sum = 0;
  for (int i = 0; i < samples; i++) {
    sum += analogRead(soundSensorPin);
    delay(10);
  }
  
  baseline = sum / samples;
  
  Serial.println("Calibration complete!");
  delay(1000);
}

Testing the Program

1. Upload the Code

Upload the code to your Vumbua Synapse Kit. During calibration, keep the environment as quiet as possible for accurate baseline measurement.

2. Open Serial Monitor

Go to Tools → Serial Monitor or press Ctrl+Shift+M. Set the baud rate to 9600.

3. Test Different Sounds

Try making different sounds (clapping, talking, snapping fingers) and observe the readings. The LED should light up based on sound intensity.

4. Adjust Sensitivity

If the sensor is too sensitive or not sensitive enough, adjust the blue potentiometer on the KY-037 module.

Understanding the Readings
Quiet (0-30) Medium (31-70) Loud (71-100)

The sound level is calculated relative to the baseline ambient noise. This makes the system adaptable to different environments.

Setting Sound Thresholds

For reliable sound detection, we need to set appropriate thresholds:

sound_threshold.ino
/*
  Vumbua Synapse Kit - Sound Detection with Thresholds
  Detect specific sound events using adjustable thresholds
*/

const int soundSensorPin = A1;
const int ledPin = 13;
const int buzzerPin = 3;  // For audio feedback

// Sound thresholds (adjust based on your environment)
const int QUIET_THRESHOLD = 15;   // Below this = quiet
const int MEDIUM_THRESHOLD = 40;  // Medium sound level
const int LOUD_THRESHOLD = 70;    // Loud sound level

// Variables
int baseline = 0;
bool soundDetected = false;
unsigned long lastSoundTime = 0;
const unsigned long DEBOUNCE_TIME = 200;  // 200ms debounce

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  
  // Calibrate baseline
  calibrateBaseline();
  
  Serial.println("Sound Detection with Thresholds");
  Serial.println("Thresholds: Quiet <15, Medium <40, Loud >=70");
}

void loop() {
  int soundValue = analogRead(soundSensorPin);
  int soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Check current sound level against thresholds
  if (soundLevel >= LOUD_THRESHOLD) {
    handleLoudSound();
  } else if (soundLevel >= MEDIUM_THRESHOLD) {
    handleMediumSound();
  } else if (soundLevel >= QUIET_THRESHOLD) {
    handleQuietSound();
  } else {
    handleSilence();
  }
  
  // Display current status
  displayStatus(soundLevel);
  
  delay(50);
}

void handleLoudSound() {
  // Debounce check
  if (millis() - lastSoundTime > DEBOUNCE_TIME) {
    Serial.println("!!! LOUD SOUND DETECTED !!!");
    digitalWrite(ledPin, HIGH);
    tone(buzzerPin, 1000, 500);
    lastSoundTime = millis();
  }
}

void handleMediumSound() {
  if (millis() - lastSoundTime > DEBOUNCE_TIME) {
    Serial.println("Medium sound detected");
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    lastSoundTime = millis();
  }
}

void handleQuietSound() {
  // Just light LED briefly for quiet sounds
  digitalWrite(ledPin, HIGH);
  delay(20);
  digitalWrite(ledPin, LOW);
}

void handleSilence() {
  digitalWrite(ledPin, LOW);
  soundDetected = false;
}

void displayStatus(int level) {
  Serial.print("Sound Level: ");
  Serial.print(level);
  Serial.print("%  |  ");
  
  if (level >= LOUD_THRESHOLD) {
    Serial.println("LOUD");
  } else if (level >= MEDIUM_THRESHOLD) {
    Serial.println("MEDIUM");
  } else if (level >= QUIET_THRESHOLD) {
    Serial.println("QUIET");
  } else {
    Serial.println("SILENT");
  }
}

void calibrateBaseline() {
  Serial.println("Calibrating baseline...");
  delay(2000);
  
  long sum = 0;
  for (int i = 0; i < 100; i++) {
    sum += analogRead(soundSensorPin);
    delay(10);
  }
  
  baseline = sum / 100;
  Serial.print("Baseline: ");
  Serial.println(baseline);
}

Adjusting Thresholds

The thresholds (QUIET_THRESHOLD, MEDIUM_THRESHOLD, LOUD_THRESHOLD) should be adjusted based on your environment:

Environment Quiet Threshold Medium Threshold Loud Threshold
Library/Quiet Room 5-10 20-30 40-50
Normal Office 10-15 30-40 60-70
Busy Classroom 20-30 50-60 80-90
Debouncing Explained

Debouncing prevents multiple detections from a single sound event. The DEBOUNCE_TIME (200ms) ensures that once a sound is detected, the system ignores subsequent detections for 200 milliseconds. This is crucial for:

  • Preventing false multiple triggers from echoes
  • Making clap detection more reliable
  • Reducing "chatter" from continuous sounds

Clap Detection System

Let's create a sophisticated clap detection system that can recognize clap patterns:

clap_detector.ino
/*
  Vumbua Synapse Kit - Clap Detection System
  Detect single claps, double claps, and clap patterns
*/

const int soundSensorPin = A1;
const int ledPin = 13;
const int buzzerPin = 3;

// Clap detection parameters
const int CLAP_THRESHOLD = 60;          // Minimum level for clap
const unsigned long CLAP_WINDOW = 300;    // Max time between claps (ms)
const unsigned long DEBOUNCE_TIME = 100;   // Min time between claps

// State variables
int baseline = 0;
bool clapDetected = false;
unsigned long lastClapTime = 0;
int clapCount = 0;
unsigned long firstClapTime = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  
  // Calibrate baseline
  calibrateBaseline();
  
  Serial.println("Clap Detection System Ready!");
  Serial.println("Try: Single clap, Double clap (within 300ms), Triple clap");
  Serial.println();
}

void loop() {
  int soundValue = analogRead(soundSensorPin);
  int soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Check for clap
  if (soundLevel >= CLAP_THRESHOLD) {
    if (!clapDetected && (millis() - lastClapTime > DEBOUNCE_TIME)) {
      handleClap();
    }
  } else {
    clapDetected = false;
  }
  
  // Check for clap pattern completion
  if (clapCount > 0 && (millis() - lastClapTime > CLAP_WINDOW)) {
    processClapPattern();
  }
  
  delay(10);  // Fast sampling for accurate timing
}

void handleClap() {
  clapDetected = true;
  unsigned long currentTime = millis();
  
  // If this is the first clap in a sequence
  if (clapCount == 0) {
    firstClapTime = currentTime;
  }
  
  clapCount++;
  lastClapTime = currentTime;
  
  // Visual and audio feedback
  Serial.print("Clap #");
  Serial.println(clapCount);
  digitalWrite(ledPin, HIGH);
  tone(buzzerPin, 800, 100);
  delay(50);
  digitalWrite(ledPin, LOW);
}

void processClapPattern() {
  Serial.print("Pattern Detected: ");
  Serial.print(clapCount);
  Serial.println(" claps");
  
  // Different actions based on clap count
  switch (clapCount) {
    case 1:
      Serial.println("Action: Toggle LED");
      toggleLED();
      playMelody(1);
      break;
      
    case 2:
      Serial.println("Action: Flash LED 3 times");
      flashLED(3);
      playMelody(2);
      break;
      
    case 3:
      Serial.println("Action: Siren effect");
      sirenEffect();
      playMelody(3);
      break;
      
    default:
      Serial.println("Action: Unknown pattern");
      errorSignal();
  }
  
  Serial.println();
  
  // Reset for next pattern
  clapCount = 0;
  firstClapTime = 0;
}

void toggleLED() {
  static bool ledState = false;
  ledState = !ledState;
  digitalWrite(ledPin, ledState ? HIGH : LOW);
}

void flashLED(int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(200);
  }
}

void sirenEffect() {
  for (int i = 0; i < 3; i++) {
    // Rising tone
    for (int freq = 500; freq <= 1500; freq += 50) {
      tone(buzzerPin, freq, 50);
      delay(20);
    }
    // Falling tone
    for (int freq = 1500; freq >= 500; freq -= 50) {
      tone(buzzerPin, freq, 50);
      delay(20);
    }
  }
}

void playMelody(int pattern) {
  int melody[] = {262, 294, 330, 349, 392, 440, 494, 523};
  
  for (int i = 0; i < pattern; i++) {
    tone(buzzerPin, melody[i], 200);
    delay(250);
  }
}

void errorSignal() {
  for (int i = 0; i < 3; i++) {
    tone(buzzerPin, 200, 100);
    delay(150);
  }
}

void calibrateBaseline() {
  Serial.println("Calibrating... Please be quiet.");
  delay(3000);
  
  long sum = 0;
  for (int i = 0; i < 200; i++) {
    sum += analogRead(soundSensorPin);
    delay(5);
  }
  
  baseline = sum / 200;
  Serial.print("Baseline calibrated: ");
  Serial.println(baseline);
}
Live Clap Detection Demo
Waiting for claps...

Try these patterns:

  • 1 clap: Toggles the LED
  • 2 claps (within 300ms): Flashes LED 3 times
  • 3 claps (within 600ms): Plays siren effect
Clap Detection Tips

For best results with clap detection:

  • Clap with your hands close to the sensor (30-50cm)
  • Make sharp, distinct claps (not soft pats)
  • Adjust the blue potentiometer for your environment
  • In noisy environments, increase CLAP_THRESHOLD
  • For double claps, clap twice within 300 milliseconds

Sound Level Meter

Create a visual sound level meter using the built-in components:

sound_level_meter.ino
/*
  Vumbua Synapse Kit - Sound Level Meter
  Visual representation of sound levels with LED bar graph effect
*/

const int soundSensorPin = A1;
const int buzzerPin = 3;

// LED pins for visual level meter (using available digital pins)
const int ledPins[] = {8, 9, 10, 11, 12, 13};
const int numLEDs = 6;

// Sound level ranges (0-100 scale)
const int levelThresholds[] = {10, 25, 40, 60, 80, 100};

// Variables
int baseline = 0;
int peakLevel = 0;
unsigned long peakTime = 0;
const unsigned long PEAK_HOLD_TIME = 1000;  // 1 second

void setup() {
  Serial.begin(9600);
  
  // Initialize LED pins
  for (int i = 0; i < numLEDs; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  
  pinMode(buzzerPin, OUTPUT);
  
  // Calibrate baseline
  calibrateBaseline();
  
  Serial.println("Sound Level Meter Active");
  Serial.println("======================");
}

void loop() {
  // Read and process sound level
  int soundValue = analogRead(soundSensorPin);
  int soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Update peak level
  if (soundLevel > peakLevel) {
    peakLevel = soundLevel;
    peakTime = millis();
  } else if (millis() - peakTime > PEAK_HOLD_TIME) {
    // Gradually decrease peak level
    peakLevel = max(0, peakLevel - 1);
  }
  
  // Update LED display
  updateLEDs(soundLevel);
  
  // Audio feedback for very loud sounds
  if (soundLevel > 80) {
    tone(buzzerPin, 1000 + (soundLevel * 10), 100);
  }
  
  // Display on Serial Monitor
  displaySoundLevel(soundLevel);
  
  delay(50);
}

void updateLEDs(int level) {
  // Turn off all LEDs first
  for (int i = 0; i < numLEDs; i++) {
    digitalWrite(ledPins[i], LOW);
  }
  
  // Light up LEDs based on sound level
  for (int i = 0; i < numLEDs; i++) {
    if (level >= levelThresholds[i]) {
      digitalWrite(ledPins[i], HIGH);
    } else {
      break;
    }
  }
  
  // Special effect for peak level (blink highest LED)
  if (peakLevel > 0 && millis() % 500 < 250) {
    for (int i = 0; i < numLEDs; i++) {
      if (peakLevel >= levelThresholds[i]) {
        digitalWrite(ledPins[i], HIGH);
      }
    }
  }
}

void displaySoundLevel(int level) {
  // Create a simple bar graph in Serial Monitor
  Serial.print("Level: ");
  Serial.print(level);
  Serial.print("%  [");
  
  int bars = map(level, 0, 100, 0, 20);
  for (int i = 0; i < 20; i++) {
    if (i < bars) {
      Serial.print("#");
    } else {
      Serial.print(".");
    }
  }
  
  Serial.print("]  Peak: ");
  Serial.print(peakLevel);
  Serial.println("%");
}

void calibrateBaseline() {
  Serial.println("Calibrating baseline noise level...");
  delay(2000);
  
  long sum = 0;
  for (int i = 0; i < 100; i++) {
    sum += analogRead(soundSensorPin);
    delay(20);
  }
  
  baseline = sum / 100;
  Serial.print("Baseline: ");
  Serial.println(baseline);
}

Understanding the LED Bar Graph

The sound level meter uses 6 LEDs to create a visual representation of sound intensity:

Sound Level Indicators
LED 1 (10%) LED 3 (40%) LED 6 (100%)
LED Pin Sound Level Color (Typical) Description
LED 1 D8 10%+ Green Very quiet sounds
LED 2 D9 25%+ Green Background noise
LED 3 D10 40%+ Yellow Normal conversation
LED 4 D11 60%+ Yellow Loud conversation
LED 5 D12 80%+ Red Shouting
LED 6 D13 100% Red (Blinking) Very loud/Peak

Practical Projects

Project 1: Sound-Activated Switch

Create a switch that turns devices on/off with claps:

clap_switch.ino
/*
  Vumbua Synapse Kit - Clap Switch
  Turn LED on/off with double clap
*/

const int soundSensorPin = A1;
const int ledPin = 13;
const int buzzerPin = 3;

// Clap detection parameters
const int CLAP_THRESHOLD = 60;
const unsigned long DOUBLE_CLAP_TIME = 500;  // Max 500ms between claps
const unsigned long DEBOUNCE_TIME = 100;

// State variables
int baseline = 0;
bool clapDetected = false;
unsigned long lastClapTime = 0;
int clapCount = 0;
bool lightState = false;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  
  calibrateBaseline();
  
  Serial.println("Clap Switch Ready!");
  Serial.println("Double clap within 500ms to toggle light");
  Serial.println();
}

void loop() {
  int soundValue = analogRead(soundSensorPin);
  int soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Check for clap
  if (soundLevel >= CLAP_THRESHOLD) {
    if (!clapDetected && (millis() - lastClapTime > DEBOUNCE_TIME)) {
      detectClap();
    }
  } else {
    clapDetected = false;
  }
  
  // Check for double clap pattern
  if (clapCount > 0 && (millis() - lastClapTime > DOUBLE_CLAP_TIME)) {
    if (clapCount == 2) {
      toggleLight();
    }
    clapCount = 0;
  }
  
  delay(10);
}

void detectClap() {
  clapDetected = true;
  clapCount++;
  lastClapTime = millis();
  
  Serial.print("Clap #");
  Serial.println(clapCount);
  
  // Visual and audio feedback
  digitalWrite(ledPin, HIGH);
  tone(buzzerPin, 800, 50);
  delay(100);
  digitalWrite(ledPin, LOW);
}

void toggleLight() {
  lightState = !lightState;
  digitalWrite(ledPin, lightState ? HIGH : LOW);
  
  Serial.print("Light turned ");
  Serial.println(lightState ? "ON" : "OFF");
  
  // Confirmation beep
  if (lightState) {
    tone(buzzerPin, 1000, 200);
  } else {
    tone(buzzerPin, 600, 200);
  }
}

void calibrateBaseline() {
  Serial.println("Calibrating...");
  delay(2000);
  
  long sum = 0;
  for (int i = 0; i < 100; i++) {
    sum += analogRead(soundSensorPin);
    delay(10);
  }
  
  baseline = sum / 100;
  Serial.print("Baseline: ");
  Serial.println(baseline);
}

Project 2: Noise Monitor with Data Logging

Create a system that monitors noise levels and provides alerts:

noise_monitor.ino
/*
  Vumbua Synapse Kit - Noise Level Monitor
  Monitor and log noise levels with time-based alerts
*/

const int soundSensorPin = A1;
const int ledPin = 13;
const int buzzerPin = 3;

// Noise level thresholds
const int QUIET_LEVEL = 30;
const int WARNING_LEVEL = 60;
const int ALERT_LEVEL = 80;

// Timing variables
const unsigned long LOG_INTERVAL = 5000;      // Log every 5 seconds
const unsigned long WARNING_DURATION = 10000;  // 10 seconds warning limit

// State variables
int baseline = 0;
unsigned long lastLogTime = 0;
unsigned long warningStartTime = 0;
bool warningActive = false;
int maxLevel = 0;
int minLevel = 100;
int totalReadings = 0;
long totalLevel = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  
  calibrateBaseline();
  
  Serial.println("Noise Level Monitor Started");
  Serial.println("==========================");
  Serial.println("Levels: Quiet<30, Warning<60, Alert>=80");
  Serial.println();
}

void loop() {
  int soundValue = analogRead(soundSensorPin);
  int soundLevel = map(constrain(soundValue - baseline, 0, 500), 0, 500, 0, 100);
  
  // Update statistics
  totalReadings++;
  totalLevel += soundLevel;
  if (soundLevel > maxLevel) maxLevel = soundLevel;
  if (soundLevel < minLevel) minLevel = soundLevel;
  
  // Check noise level and take action
  checkNoiseLevel(soundLevel);
  
  // Log statistics periodically
  if (millis() - lastLogTime >= LOG_INTERVAL) {
    logStatistics();
    lastLogTime = millis();
  }
  
  delay(100);
}

void checkNoiseLevel(int level) {
  if (level >= ALERT_LEVEL) {
    // Immediate alert for very loud noise
    Serial.println("!!! ALERT: Excessive Noise !!!");
    soundAlert();
    warningStartTime = millis();
    warningActive = true;
    
  } else if (level >= WARNING_LEVEL) {
    // Warning for moderately loud noise
    if (!warningActive) {
      warningStartTime = millis();
      warningActive = true;
      Serial.println("Warning: High noise level detected");
    }
    
    // Check if warning has been active too long
    if (millis() - warningStartTime >= WARNING_DURATION) {
      Serial.println("Warning: Prolonged high noise level!");
      soundWarning();
      warningStartTime = millis();  // Reset timer
    }
    
    digitalWrite(ledPin, HIGH);
    
  } else if (level >= QUIET_LEVEL) {
    // Normal operation - blink LED slowly
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    warningActive = false;
    
  } else {
    // Quiet - turn off LED
    digitalWrite(ledPin, LOW);
    warningActive = false;
  }
}

void soundAlert() {
  // Loud, urgent alert pattern
  for (int i = 0; i < 3; i++) {
    tone(buzzerPin, 1200, 200);
    delay(300);
  }
}

void soundWarning() {
  // Gentle warning pattern
  tone(buzzerPin, 800, 500);
  delay(600);
}

void logStatistics() {
  int avgLevel = totalLevel / totalReadings;
  
  Serial.println("=== Noise Level Statistics ===");
  Serial.print("Time: ");
  Serial.print(millis() / 1000);
  Serial.println(" seconds");
  Serial.print("Readings: ");
  Serial.println(totalReadings);
  Serial.print("Average: ");
  Serial.print(avgLevel);
  Serial.println("%");
  Serial.print("Minimum: ");
  Serial.print(minLevel);
  Serial.println("%");
  Serial.print("Maximum: ");
  Serial.print(maxLevel);
  Serial.println("%");
  
  if (avgLevel > WARNING_LEVEL) {
    Serial.println("STATUS: High average noise level!");
  } else if (avgLevel > QUIET_LEVEL) {
    Serial.println("STATUS: Moderate noise level");
  } else {
    Serial.println("STATUS: Quiet environment");
  }
  
  Serial.println();
  
  // Reset statistics for next period
  totalReadings = 0;
  totalLevel = 0;
  maxLevel = 0;
  minLevel = 100;
}

void calibrateBaseline() {
  Serial.println("Calibrating baseline...");
  delay(3000);
  
  long sum = 0;
  for (int i = 0; i < 200; i++) {
    sum += analogRead(soundSensorPin);
    delay(10);
  }
  
  baseline = sum / 200;
  Serial.print("Baseline calibrated: ");
  Serial.println(baseline);
}

ATmega328P ADC (Analog-to-Digital Converter)

The ATmega328P microcontroller in your Vumbua Synapse Kit has a built-in 10-bit ADC (Analog-to-Digital Converter) that makes it perfect for sound sensor applications.

10-bit Resolution

The ADC converts analog voltages (0-5V) to digital values (0-1023):

  • 0V → 0 (digital value)
  • 2.5V → 512
  • 5V → 1023
  • Resolution: 5V ÷ 1024 = 4.88mV per step

This high resolution allows us to detect subtle changes in sound intensity.

Sampling Rate

The ATmega328P can sample analog signals at up to 15kHz (15,000 samples per second). For sound applications, we typically sample at:

  • 50-100Hz: For general sound level monitoring
  • 1-2kHz: For clap detection and pattern recognition
  • 10kHz+: For audio recording (not possible with KY-037)

Our code samples at about 100Hz (10ms delay between readings), which is sufficient for most sound detection applications.

Pin A1 Specifics

On the Vumbua Synapse Kit, the sound sensor is connected to Analog Pin 1 (A1):

  • Arduino Pin: A1 (Analog Input 1)
  • ATmega328P Pin: PC1 (Pin 24)
  • ADC Channel: ADC1 (Channel 1)
  • Reference Voltage: Default 5V (AREF)

This pin is dedicated for analog input and has excellent noise immunity for accurate sound measurements.

Why A1 for Sound Sensor?

On the Vumbua Synapse Kit, A1 was chosen for the sound sensor because:

  • It's a dedicated analog input pin
  • Has good separation from digital noise sources
  • Close to GND and 5V pins for clean power
  • Not used by other critical functions
  • Allows for easy expansion with other analog sensors

Troubleshooting Common Issues

Common KY-037 Problems

  • Check if blue potentiometer is turned clockwise (increases sensitivity)
  • Make sure you're clapping/talking close to the sensor (30-50cm)
  • Verify Serial Monitor baud rate is set to 9600
  • Check that you're reading from pin A1 (not A0 or other pins)
  • Ensure baseline calibration completed successfully
  • Try adjusting CLAP_THRESHOLD value in the code

  • Turn blue potentiometer counter-clockwise (decreases sensitivity)
  • Increase threshold values in code (QUIET_THRESHOLD, etc.)
  • Improve baseline calibration (ensure quiet environment during calibration)
  • Add software debouncing (already included in our code)
  • Move away from constant noise sources (fans, air conditioners)
  • Consider using averaging of multiple samples

  • Make sharp, distinct claps (not soft pats)
  • Clap at consistent distance from sensor (30-50cm ideal)
  • Adjust DOUBLE_CLAP_TIME constant (try 300-800ms)
  • Increase CLAP_THRESHOLD if detecting false positives
  • Add more samples in baseline calibration (200-500 samples)
  • Ensure stable power supply (use good quality USB cable)

  • Add capacitor (10-100µF) between VCC and GND on sensor module
  • Use software filtering (averaging multiple readings)
  • Increase delay between readings (reduce sampling rate)
  • Keep sensor away from electromagnetic interference
  • Use shielded cable if extending sensor connection
  • Ensure good ground connection between all components

Video Demonstration

Sound Sensor Video Tutorial

Watch our detailed video walkthrough demonstrating all the projects in this lesson.

Learn proper clap techniques, sensor calibration, and project demonstrations.

Watch on OLSPACE YouTube

What's Next?

Congratulations! You've successfully mastered sound detection with the KY-037 sensor. Here's what you've accomplished:

  • ✓ Learned how sound sensors work and their applications
  • ✓ Programmed the KY-037 sensor on pin A1
  • ✓ Created sound level monitoring systems
  • ✓ Built sophisticated clap detection with pattern recognition
  • ✓ Developed practical projects like clap switches and noise monitors
  • ✓ Learned about ATmega328P ADC capabilities

In the next lesson, you'll explore visual output with LCD displays:

Lesson 8: LCD 16x2 Display

Learn to display text and data on a 16x2 character LCD screen. Create information displays, menus, and real-time data viewers for your sensor projects.

Resources & Downloads