Video
# Lab: Sound Alert Defender - Intelligent Sound Detection System
## **Objective**
Build a voice-activated security system that monitors ambient sound levels and activates an alarm when loud sounds are detected. The system includes manual override controls, status indicators, and configurable sensitivity settings.
## **Required Components**

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
4. **TinkerBlock TK36** - Active Buzzer Module
5. **TinkerBlock TK01** - LED Module
6. **TinkerBlock TK04** - Push Button Module
## **Theory**
### **Voice-Activated Security System**
- **Sound Monitoring**: Continuous monitoring of ambient sound levels
- **Threshold Detection**: Alarm triggers when sound exceeds preset threshold
- **False Alarm Prevention**: Noise filtering and debouncing mechanisms
- **Manual Control**: Override button for system control
### **Security System States**
- **Armed**: System actively monitoring for sounds
- **Alarm**: Loud sound detected, alarm activated
- **Disarmed**: System temporarily disabled
### **Sound Detection Algorithm**
- **Baseline Calibration**: Normal ambient level around 500-600
- **Threshold Setting**: Configurable sensitivity levels
- **Duration Filtering**: Minimum duration to prevent false alarms
- **Pattern Recognition**: Distinguish between normal and suspicious sounds
## **Wiring Instructions**
### **TK27 Analog Microphone Pinout**
- **GND** → Arduino GND
- **VCC** → Arduino 5V
- **NC** → No Connection
- **Signal** → Arduino Analog Pin A3
### **TK36 Active Buzzer Pinout**
- **GND** → Arduino GND
- **VCC** → Arduino 5V
- **NC** → No Connection
- **Signal** → Arduino Digital Pin D9
### **TK01 LED Module Pinout**
- **GND** → Arduino GND
- **VCC** → Arduino 5V
- **NC** → No Connection
- **Signal** → Arduino Digital Pin D3
### **TK04 Push Button Pinout**
- **GND** → Arduino GND
- **VCC** → Arduino 5V
- **NC** → No Connection
- **Signal** → Arduino Digital Pin D5
### **Connection Diagram**

```
UNO R3 + Shield
├── Analog Pin A3 ───→ TK27 Signal (Microphone)
├── Digital Pin D3 ──→ TK01 Signal (Status LED)
├── Digital Pin D5 ──→ TK04 Signal (Control Button)
└── Digital Pin D9 ──→ TK36 Signal (Alarm Buzzer)
```
## **Basic Security System**
```cpp
// Basic Voice-Activated Security System
// Monitors sound levels and activates alarm on loud sounds
// Pin definitions
#define MIC_PIN A3 // TK27 Analog Microphone on A3
#define LED_PIN 3 // TK01 LED on D3
#define BUTTON_PIN 5 // TK04 Push Button on D5
#define BUZZER_PIN 9 // TK36 Active Buzzer on D9
// System parameters
#define BASELINE 550 // Normal ambient sound level (5xx)
#define ALARM_THRESHOLD 50 // Sound level increase to trigger alarm
#define ALARM_DURATION 2000 // Minimum alarm duration (ms)
#define DEBOUNCE_TIME 50 // Button debounce time (ms)
// System states
enum SystemState {
STATE_ARMED, // System monitoring
STATE_ALARM, // Alarm activated
STATE_DISARMED // System disabled
};
// Variables
SystemState currentState = STATE_ARMED;
int soundLevel = 0;
int lastSoundLevel = 0;
unsigned long alarmStartTime = 0;
unsigned long lastButtonPress = 0;
bool buttonPressed = false;
bool lastButtonState = false;
int alarmCount = 0;
void setup() {
// Initialize serial communication
Serial.begin(9600);
Serial.println("Voice-Activated Security System");
Serial.println("===============================");
// Initialize pins
pinMode(MIC_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
// Start with LED off and buzzer off
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
delay(1000);
Serial.println("Security system initialized!");
Serial.println("TK27 Microphone: A3");
Serial.println("TK01 LED: D3");
Serial.println("TK04 Button: D5");
Serial.println("TK36 Buzzer: D9");
Serial.println();
Serial.println("System Status: ARMED");
Serial.println("Press button to disarm/arm");
Serial.println();
}
void loop() {
// Read microphone input
soundLevel = analogRead(MIC_PIN);
// Handle button input
handleButton();
// Process system state
switch (currentState) {
case STATE_ARMED:
handleArmedState();
break;
case STATE_ALARM:
handleAlarmState();
break;
case STATE_DISARMED:
handleDisarmedState();
break;
}
// Update status LED
updateStatusLED();
// Display system info
displaySystemInfo();
delay(100);
}
void handleButton() {
// Read button state (inverted for pull-up)
bool currentButtonState = !digitalRead(BUTTON_PIN);
// Handle button press (rising edge)
if (currentButtonState && !lastButtonState) {
buttonPressed = true;
lastButtonPress = millis();
Serial.println("Button pressed!");
}
// Handle button release (falling edge)
if (!currentButtonState && lastButtonState) {
buttonPressed = false;
unsigned long pressDuration = millis() - lastButtonPress;
// Priority: Stop alarm first, then handle other functions
if (currentState == STATE_ALARM && pressDuration > DEBOUNCE_TIME) {
// Stop alarm immediately when button is pressed
currentState = STATE_ARMED;
stopAlarm();
Serial.println("Alarm stopped. System ARMED");
} else if (pressDuration > DEBOUNCE_TIME) {
// Short press - toggle armed/disarmed
toggleSystemState();
}
}
lastButtonState = currentButtonState;
}
void handleArmedState() {
// Check for loud sounds
int soundDifference = abs(soundLevel - BASELINE);
if (soundDifference > ALARM_THRESHOLD) {
// Loud sound detected - trigger alarm
if (currentState != STATE_ALARM) {
triggerAlarm();
}
}
}
void handleAlarmState() {
// Continue alarm until manually stopped
// Alarm will continue until button is pressed
// Optional: Auto-reset after certain time
if (millis() - alarmStartTime > 30000) { // 30 seconds
Serial.println("Auto-resetting alarm...");
currentState = STATE_ARMED;
stopAlarm();
}
}
void handleDisarmedState() {
// System is disabled - no monitoring
// Wait for button press to re-arm
}
void triggerAlarm() {
currentState = STATE_ALARM;
alarmStartTime = millis();
alarmCount++;
Serial.println("*** ALARM TRIGGERED! ***");
Serial.print("Sound level: ");
Serial.print(soundLevel);
Serial.print(" | Difference: ");
Serial.println(abs(soundLevel - BASELINE));
// Activate alarm
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
}
void stopAlarm() {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
Serial.println("Alarm stopped.");
}
void toggleSystemState() {
if (currentState == STATE_ARMED) {
currentState = STATE_DISARMED;
Serial.println("System DISARMED");
} else if (currentState == STATE_DISARMED) {
currentState = STATE_ARMED;
Serial.println("System ARMED");
} else if (currentState == STATE_ALARM) {
currentState = STATE_ARMED;
stopAlarm();
Serial.println("Alarm stopped. System ARMED");
}
}
void updateStatusLED() {
switch (currentState) {
case STATE_ARMED:
// Slow blink - armed
if ((millis() / 1000) % 2 == 0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
break;
case STATE_ALARM:
// Fast blink - alarm
if ((millis() / 200) % 2 == 0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
break;
case STATE_DISARMED:
// Off - disarmed
digitalWrite(LED_PIN, LOW);
break;
}
}
void displaySystemInfo() {
static unsigned long lastDisplay = 0;
if (millis() - lastDisplay > 2000) {
Serial.print("Status: ");
switch (currentState) {
case STATE_ARMED:
Serial.print("ARMED");
break;
case STATE_ALARM:
Serial.print("ALARM");
break;
case STATE_DISARMED:
Serial.print("DISARMED");
break;
}
Serial.print(" | Sound: ");
Serial.print(soundLevel);
Serial.print(" | Alarms: ");
Serial.println(alarmCount);
lastDisplay = millis();
}
}
```
## **Code Explanation**
### **System Architecture Overview**
The Sound Alert Defender uses a **state machine design** with three main states: **ARMED**, **ALARM**, and **DISARMED**. This architecture ensures clean separation of concerns and predictable behavior.
### **Core Components Analysis**
#### **1. Pin Configuration & Hardware Interface**
```cpp
#define MIC_PIN A3 // TK27 Analog Microphone on A3
#define LED_PIN 3 // TK01 LED on D3
#define BUTTON_PIN 5 // TK04 Push Button on D5
#define BUZZER_PIN 9 // TK36 Active Buzzer on D9
```
- **Analog Input (A3)**: Reads continuous sound levels (0-1023 range)
- **Digital Output (D3)**: Controls status LED with PWM capability
- **Digital Input (D5)**: Button with internal pull-up resistor
- **Digital Output (D9)**: Controls active buzzer for alarm sounds
#### **2. System Parameters & Calibration**
```cpp
#define BASELINE 550 // Normal ambient sound level (5xx)
#define ALARM_THRESHOLD 50 // Sound level increase to trigger alarm
#define ALARM_DURATION 2000 // Minimum alarm duration (ms)
#define DEBOUNCE_TIME 50 // Button debounce time (ms)
```
- **BASELINE**: Represents normal ambient noise (~550 in typical environments)
- **ALARM_THRESHOLD**: Sensitivity setting (lower = more sensitive)
- **ALARM_DURATION**: Prevents false alarms from brief sounds
- **DEBOUNCE_TIME**: Eliminates button bounce artifacts
#### **3. State Machine Implementation**
```cpp
enum SystemState {
STATE_ARMED, // System monitoring
STATE_ALARM, // Alarm activated
STATE_DISARMED // System disabled
};
```
- **STATE_ARMED**: Active monitoring mode with sound detection
- **STATE_ALARM**: Alarm triggered, visual/audio alerts active
- **STATE_DISARMED**: System disabled, no monitoring
### **Key Functions Deep Dive**
#### **1. Sound Detection Algorithm**
```cpp
void handleArmedState() {
// Check for loud sounds
int soundDifference = abs(soundLevel - BASELINE);
if (soundDifference > ALARM_THRESHOLD) {
// Loud sound detected - trigger alarm
if (currentState != STATE_ALARM) {
triggerAlarm();
}
}
}
```
**How it works:**
- **Baseline Comparison**: Calculates difference from normal ambient level
- **Absolute Value**: Detects both increases and decreases in sound
- **Threshold Check**: Triggers alarm when difference exceeds sensitivity
- **State Protection**: Prevents multiple alarm triggers
#### **2. Button Input Processing**
```cpp
void handleButton() {
// Read button state (inverted for pull-up)
bool currentButtonState = !digitalRead(BUTTON_PIN);
// Handle button press (rising edge)
if (currentButtonState && !lastButtonState) {
buttonPressed = true;
lastButtonPress = millis();
Serial.println("Button pressed!");
}
// Handle button release (falling edge)
if (!currentButtonState && lastButtonState) {
buttonPressed = false;
unsigned long pressDuration = millis() - lastButtonPress;
// Priority: Stop alarm first, then handle other functions
if (currentState == STATE_ALARM && pressDuration > DEBOUNCE_TIME) {
// Stop alarm immediately when button is pressed
currentState = STATE_ARMED;
stopAlarm();
Serial.println("Alarm stopped. System ARMED");
} else if (pressDuration > DEBOUNCE_TIME) {
// Short press - toggle armed/disarmed
toggleSystemState();
}
}
lastButtonState = currentButtonState;
}
```
**Key Features:**
- **Edge Detection**: Detects button press and release separately
- **Debouncing**: Eliminates false triggers from button bounce
- **Priority Logic**: Alarm stopping takes precedence over other functions
- **Duration Measurement**: Tracks how long button is held
#### **3. Alarm Management System**
```cpp
void triggerAlarm() {
currentState = STATE_ALARM;
alarmStartTime = millis();
alarmCount++;
Serial.println("*** ALARM TRIGGERED! ***");
Serial.print("Sound level: ");
Serial.print(soundLevel);
Serial.print(" | Difference: ");
Serial.println(abs(soundLevel - BASELINE));
// Activate alarm
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
}
void handleAlarmState() {
// Continue alarm until manually stopped
// Alarm will continue until button is pressed
// Optional: Auto-reset after certain time
if (millis() - alarmStartTime > 30000) { // 30 seconds
Serial.println("Auto-resetting alarm...");
currentState = STATE_ARMED;
stopAlarm();
}
}
```
**Alarm Features:**
- **Immediate Activation**: LED and buzzer turn on instantly
- **Persistent Alert**: Continues until manually stopped
- **Auto-Reset**: Safety feature prevents infinite alarms
- **Event Logging**: Tracks alarm count and timing
#### **4. Status LED Management**
```cpp
void updateStatusLED() {
switch (currentState) {
case STATE_ARMED:
// Slow blink - armed
if ((millis() / 1000) % 2 == 0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
break;
case STATE_ALARM:
// Fast blink - alarm
if ((millis() / 200) % 2 == 0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
break;
case STATE_DISARMED:
// Off - disarmed
digitalWrite(LED_PIN, LOW);
break;
}
}
```
**LED Patterns:**
- **ARMED**: Slow blink (1 second intervals) - system is active
- **ALARM**: Fast blink (0.2 second intervals) - urgent attention needed
- **DISARMED**: Off - system is inactive
### **Performance Optimizations**
#### **1. Non-Blocking Design**
- **No delay() calls**: System remains responsive
- **millis() timing**: Precise timing without blocking
- **State-based processing**: Efficient resource usage
#### **2. Memory Efficiency**
- **Minimal variables**: Optimized memory footprint
- **Static variables**: Persistent state without global scope
- **Efficient algorithms**: Simple but effective calculations
#### **3. Real-time Responsiveness**
- **Fast loop execution**: 100ms cycle time
- **Immediate button response**: No lag in user interaction
- **Quick alarm activation**: Sub-second response time
### **Error Handling & Safety Features**
#### **1. Button Debouncing**
- **Hardware debouncing**: Internal pull-up resistors
- **Software debouncing**: Timing-based validation
- **Edge detection**: Reliable button state changes
#### **2. Alarm Safety**
- **Auto-reset**: Prevents infinite alarm loops
- **Manual override**: Immediate alarm stopping
- **State protection**: Prevents multiple triggers
#### **3. System Stability**
- **Baseline calibration**: Adapts to environment
- **Threshold validation**: Prevents invalid settings
- **State consistency**: Maintains system integrity
### **Integration with TinkerBlock Modules**
#### **1. TK27 Analog Microphone**
- **Analog Input**: 0-1023 range for sound levels
- **Sensitivity**: Detects quiet to loud sounds
- **Response Time**: Fast analog-to-digital conversion
#### **2. TK01 LED Module**
- **Digital Control**: Simple on/off operation
- **PWM Capable**: Can be extended for dimming effects
- **Visual Feedback**: Clear status indication
#### **3. TK04 Push Button**
- **Pull-up Configuration**: Reliable input detection
- **Mechanical Switch**: Durable and responsive
- **User Interface**: Primary control method
#### **4. TK36 Active Buzzer**
- **Digital Control**: Simple on/off operation
- **Loud Output**: Effective alarm sound
- **Low Power**: Efficient operation
### **Extensibility & Customization**
#### **1. Easy Parameter Adjustment**
- **Threshold tuning**: Adjust sensitivity for environment
- **Timing modification**: Change alarm durations
- **LED patterns**: Customize visual feedback
#### **2. Additional Features**
- **Multiple sensors**: Add more microphones for coverage
- **Wireless communication**: Add Bluetooth/WiFi modules
- **Data logging**: Record alarm events and patterns
- **Mobile interface**: Create smartphone app control
#### **3. Advanced Algorithms**
- **Pattern recognition**: Distinguish sound types
- **Machine learning**: Adaptive sensitivity
- **Multi-zone monitoring**: Area-specific detection
This modular design makes the system easy to understand, modify, and extend for various security applications.
## **Troubleshooting**
### **Microphone Issues:**
- Check TK27 wiring (A3 pin)
- Verify baseline level (~550)
- Test with simple analogRead
- Check for electrical interference
### **Buzzer Issues:**
- Check TK36 wiring (D9 pin)
- Verify power connections (5V, GND)
- Test with simple digitalWrite
- Check for pin conflicts
### **LED Issues:**
- Check TK01 wiring (D3 pin)
- Verify power connections
- Test with simple digitalWrite
- Check for loose connections
### **Button Issues:**
- Check TK04 wiring (D5 pin)
- Verify pull-up resistor configuration
- Test with simple digitalRead
- Check for loose connections
### **Calibration Issues:**
- Adjust baseline value for your environment
- Modify threshold for sensitivity
- Test in different acoustic environments
- Check for background noise sources
## **Applications**
### **Home Security**
- **Intruder Detection**: Detect unauthorized entry
- **Glass Break Detection**: Monitor for breaking sounds
- **Pet Monitoring**: Monitor pet activity
- **Baby Monitor**: Monitor infant sounds
### **Commercial Security**
- **Office Security**: Monitor after-hours activity
- **Retail Security**: Detect shoplifting attempts
- **Warehouse Security**: Monitor storage areas
- **Construction Site**: Monitor equipment and activity
### **Industrial Monitoring**
- **Equipment Monitoring**: Detect machinery malfunctions
- **Safety Systems**: Monitor for dangerous conditions
- **Quality Control**: Monitor production processes
- **Environmental Monitoring**: Monitor workplace conditions
### **Educational**
- **Sound Analysis**: Learn about audio signal processing
- **Security Systems**: Understand security system design
- **Embedded Systems**: Practice real-time system design
- **Sensor Integration**: Learn about sensor networks
## **Next Steps**
- Add wireless communication
- Implement multiple sensor zones
- Add recording capabilities
- Create mobile app interface
## **Resources**
- **Security Systems**: Professional security system design
- **Audio Processing**: Digital signal processing techniques
- **Embedded Systems**: Real-time system design
- **Sensor Networks**: Multi-sensor system integration