02 - Lab Sound Detection Master

Video

# Lab: **Sound Detection Master - Analog Microphone Applications** ## **Objective** Master the TK27 Analog Microphone module through comprehensive applications including sound detection, volume measurement, audio visualization, voice recognition, and interactive sound control. Learn to process analog audio signals and create responsive sound-activated systems. ## **Required Components** ![](https://cdn.shopify.com/s/files/1/0331/9994/7908/files/Pasted_image_20250723165313.png?v=1753857916) 1. **Lonely Binary UNO R3** - Main Arduino board 2. **TinkerBlock UNO R3 Shield** - Expansion shield that plugs onto the UNO R3 3. **TinkerBlock TK27** - Analog Microphone Module ## **Theory** ### **Analog Microphone Operation** - **Sound Waves**: Converted to electrical signals - **Analog Output**: Continuous voltage variation (0-5V) - **Sensitivity**: Responds to sound pressure changes - **Frequency Response**: Typically 20Hz - 20kHz human hearing range ### **Signal Characteristics** - **Quiet Environment**: Lower voltage readings - **Loud Sounds**: Higher voltage readings - **Dynamic Range**: Voltage swing based on sound intensity - **Noise Floor**: Minimum detectable signal level ### **Applications** - **Sound Detection**: Detect presence of sound and trigger actions - **Volume Measurement**: Quantify sound intensity with precision - **Audio Visualization**: Real-time sound level display and analysis - **Voice Recognition**: Pattern analysis for voice commands and identification - **Noise Monitoring**: Environmental sound level tracking and alerting - **Interactive Systems**: Sound-activated lighting and control systems - **Audio Recording**: Basic audio signal capture and processing - **Sound Classification**: Distinguish between different types of sounds ## **Wiring Instructions** ### **TK27 Analog Microphone Pinout** - **GND** → Arduino GND - **VCC** → Arduino 5V - **NC** → No Connection - **Signal** → Arduino Analog Pin A0 ### **Connection Diagram** ![](https://cdn.shopify.com/s/files/1/0331/9994/7908/files/Pasted_image_20250723165328.png?v=1753857921) ``` UNO R3 + Shield └── Analog Pin A0 ──→ TK27 Signal ``` ## **Sound Detection Code** ```cpp // Sound Detection with TK27 Analog Microphone // Pin definitions #define MIC_PIN A0 // TK27 Microphone on A0 // Threshold values #define QUIET_THRESHOLD 520 // Threshold for quiet environment #define SOUND_THRESHOLD 550 // Threshold for sound detection #define LOUD_THRESHOLD 700 // Threshold for loud sounds #define VERY_LOUD_THRESHOLD 800 // Threshold for very loud sounds // Variables int soundValue = 0; // Current sound reading int maxSound = 0; // Maximum sound level detected int minSound = 1023; // Minimum sound level detected unsigned long lastUpdate = 0; // Last update time const unsigned long UPDATE_INTERVAL = 100; // Update interval (ms) void setup() { // Initialize serial communication Serial.begin(9600); Serial.println("TK27 Analog Microphone - Basic Sound Detection"); Serial.println("=============================================="); // Initialize analog pin pinMode(MIC_PIN, INPUT); delay(1000); Serial.println("Microphone initialized!"); Serial.println("Speak, clap, or make sounds to see the response."); Serial.println("Thresholds:"); Serial.print("Quiet: < "); Serial.println(QUIET_THRESHOLD); Serial.print("Sound: > "); Serial.println(SOUND_THRESHOLD); Serial.print("Loud: > "); Serial.println(LOUD_THRESHOLD); Serial.print("Very Loud: > "); Serial.println(VERY_LOUD_THRESHOLD); Serial.println(); } void loop() { // Read microphone value soundValue = analogRead(MIC_PIN); // Update min/max values if (soundValue > maxSound) { maxSound = soundValue; } if (soundValue < minSound) { minSound = soundValue; } // Update display every 100ms if (millis() - lastUpdate >= UPDATE_INTERVAL) { displaySoundInfo(); lastUpdate = millis(); } // Small delay for stability delay(10); } void displaySoundInfo() { // Clear line and display current reading Serial.print("Current: "); Serial.print(soundValue); Serial.print(" | "); // Determine sound level if (soundValue < QUIET_THRESHOLD) { Serial.print("Status: QUIET "); } else if (soundValue < SOUND_THRESHOLD) { Serial.print("Status: LOW "); } else if (soundValue < LOUD_THRESHOLD) { Serial.print("Status: MEDIUM "); } else if (soundValue < VERY_LOUD_THRESHOLD) { Serial.print("Status: LOUD "); } else { Serial.print("Status: VERY LOUD "); } // Display range Serial.print(" | Range: "); Serial.print(minSound); Serial.print("-"); Serial.print(maxSound); // Display simple bar graph Serial.print(" | ["); int barLength = map(soundValue, 0, 1023, 0, 20); for (int i = 0; i < 20; i++) { if (i < barLength) { Serial.print("#"); } else { Serial.print(" "); } } Serial.println("]"); } ``` ## **Code Explanation** ### **Pin and Threshold Configuration** ```cpp #define MIC_PIN A0 // TK27 Microphone on A0 #define QUIET_THRESHOLD 520 // Threshold for quiet environment #define SOUND_THRESHOLD 550 // Threshold for sound detection #define LOUD_THRESHOLD 700 // Threshold for loud sounds #define VERY_LOUD_THRESHOLD 800 // Threshold for very loud sounds ``` - **Analog Pin A0**: Reads continuous voltage from microphone (0-1023) - **Threshold Levels**: Multiple levels for different sound classifications - **Calibration**: Thresholds may need adjustment based on environment - **Dynamic Range**: Covers quiet to very loud sound levels ### **Variable Management** ```cpp int soundValue = 0; // Current sound reading int maxSound = 0; // Maximum sound level detected int minSound = 1023; // Minimum sound level detected unsigned long lastUpdate = 0; // Last update time const unsigned long UPDATE_INTERVAL = 100; // Update interval (ms) ``` - **Real-time Reading**: `soundValue` stores current analog reading - **Range Tracking**: `maxSound` and `minSound` track sound extremes - **Update Control**: `lastUpdate` and `UPDATE_INTERVAL` control display frequency - **Memory Efficiency**: Only updates display every 100ms to reduce serial traffic ### **Setup Function** ```cpp void setup() { Serial.begin(9600); Serial.println("TK27 Analog Microphone - Basic Sound Detection"); Serial.println("=============================================="); pinMode(MIC_PIN, INPUT); delay(1000); Serial.println("Microphone initialized!"); Serial.println("Speak, clap, or make sounds to see the response."); Serial.println("Thresholds:"); Serial.print("Quiet: < "); Serial.println(QUIET_THRESHOLD); // ... more threshold displays } ``` - **Serial Communication**: 9600 baud rate for data transmission - **Pin Configuration**: Sets A0 as input for analog reading - **User Guidance**: Displays thresholds and instructions - **Initialization Delay**: 1-second delay for system stability ### **Main Loop Logic** ```cpp void loop() { // Read microphone value soundValue = analogRead(MIC_PIN); // Update min/max values if (soundValue > maxSound) { maxSound = soundValue; } if (soundValue < minSound) { minSound = soundValue; } // Update display every 100ms if (millis() - lastUpdate >= UPDATE_INTERVAL) { displaySoundInfo(); lastUpdate = millis(); } delay(10); } ``` - **Continuous Reading**: `analogRead()` provides real-time sound levels - **Range Tracking**: Updates min/max values for dynamic range analysis - **Timed Updates**: Only displays every 100ms to prevent serial overflow - **Stability Delay**: 10ms delay ensures stable readings ### **Sound Level Classification** ```cpp if (soundValue < QUIET_THRESHOLD) { Serial.print("Status: QUIET "); } else if (soundValue < SOUND_THRESHOLD) { Serial.print("Status: LOW "); } else if (soundValue < LOUD_THRESHOLD) { Serial.print("Status: MEDIUM "); } else if (soundValue < VERY_LOUD_THRESHOLD) { Serial.print("Status: LOUD "); } else { Serial.print("Status: VERY LOUD "); } ``` - **Threshold-Based Classification**: Uses predefined levels to categorize sound - **Progressive Levels**: Quiet → Low → Medium → Loud → Very Loud - **Real-time Status**: Updates status based on current reading - **User-Friendly Labels**: Clear, descriptive status messages ### **Visual Bar Graph Generation** ```cpp Serial.print(" | ["); int barLength = map(soundValue, 0, 1023, 0, 20); for (int i = 0; i < 20; i++) { if (i < barLength) { Serial.print("#"); } else { Serial.print(" "); } } Serial.println("]"); ``` - **Value Mapping**: Maps 0-1023 analog range to 0-20 bar length - **Visual Representation**: Creates ASCII bar graph for easy visualization - **Real-time Updates**: Bar length changes with sound intensity - **Space Efficiency**: Uses 20 characters for compact display ### **Key Programming Concepts** #### **Analog Signal Processing** - **Continuous Reading**: Analog values provide smooth, continuous data - **Noise Handling**: Averaging and filtering techniques for clean signals - **Threshold Detection**: Reliable sound detection using calibrated levels - **Dynamic Range**: Handles wide range of sound intensities #### **Real-time Data Management** - **Efficient Updates**: Timed updates prevent system overload - **Memory Management**: Minimal variable usage for efficiency - **Range Tracking**: Maintains historical min/max values - **Status Persistence**: Tracks sound levels over time #### **User Interface Design** - **Clear Display**: Organized, readable output format - **Visual Feedback**: Bar graph provides immediate visual understanding - **Status Information**: Real-time sound level classification - **Range Information**: Shows detected sound range for calibration #### **System Optimization** - **Update Frequency**: Balances responsiveness with performance - **Serial Efficiency**: Reduces serial traffic with timed updates - **Memory Usage**: Minimal variable allocation - **Processing Speed**: Fast loop execution for real-time response ## **Expected Output** ### **Serial Monitor Output** ``` TK27 Analog Microphone - Basic Sound Detection ============================================== Microphone initialized! Speak, clap, or make sounds to see the response. Thresholds: Quiet: < 520 Sound: > 550 Loud: > 700 Very Loud: > 800 Current: 512 | Status: QUIET | Range: 510-520 | [########## ] Current: 580 | Status: MEDIUM | Range: 510-580 | [############ ] Current: 720 | Status: LOUD | Range: 510-720 | [################## ] Current: 850 | Status: VERY LOUD | Range: 510-850 | [####################] Current: 530 | Status: LOW | Range: 510-850 | [########## ] ``` ### **Visual Output** - **Real-time Bar Graph**: ASCII bar that grows with sound intensity - **Status Updates**: Clear sound level classification - **Range Display**: Shows detected min/max values - **Continuous Monitoring**: Live updates every 100ms ### **Behavior Patterns** - **Quiet Environment**: Low readings, short bar graph - **Normal Speech**: Medium readings, moderate bar length - **Loud Sounds**: High readings, long bar graph - **Sudden Noises**: Rapid bar graph changes - **Background Noise**: Stable, low-level readings ## **Troubleshooting** ### **Reading Issues:** - **No Response**: Check wiring (A0 pin connection) - **Constant High Values**: Check power supply and grounding - **Erratic Readings**: Ensure stable power and proper shielding - **Low Sensitivity**: Adjust thresholds or check microphone placement ### **Calibration Problems:** - **Incorrect Thresholds**: Test in your specific environment - **Poor Classification**: Fine-tune threshold values - **Range Issues**: Check min/max value tracking - **Update Problems**: Verify timing and serial communication ### **Performance Issues:** - **Slow Response**: Reduce UPDATE_INTERVAL for faster updates - **Serial Overflow**: Increase UPDATE_INTERVAL to reduce traffic - **Memory Problems**: Check variable usage and optimization - **Power Issues**: Ensure adequate power supply for microphone ### **Environmental Factors:** - **Background Noise**: Adjust thresholds for your environment - **Microphone Placement**: Position for optimal sound capture - **Interference**: Keep away from electrical noise sources - **Temperature Effects**: Account for temperature-related sensitivity changes