Tuesday, July 23, 2024

LED Control using Mic

 const int micPin = A0;  // Analog pin connected to the microphone sensor

const int ledPin = 8;   // Digital pin connected to an LED
const int threshold = 500; // Sound threshold for detecting a clap

bool ledState = false;  // To track the state of the LED
unsigned long lastClapTime = 0; // To store the time of the last clap

void setup() {
  pinMode(micPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);   // Initialize serial communication for debugging
}

void loop() {
  int soundLevel = analogRead(micPin); // Read the sound level
  Serial.println(soundLevel);          // Print sound level to the Serial Monitor
 
  // Check if the sound level exceeds the threshold
  if (soundLevel > threshold) {
    // Ensure a delay between clap detections to avoid multiple detections for a single clap
    if (millis() - lastClapTime > 500) { // 500 ms debounce time
      ledState = !ledState;             // Toggle the LED state
      digitalWrite(ledPin, ledState);   // Update the LED
      lastClapTime = millis();          // Update the time of the last clap
    }
  }

  delay(10); // Short delay to stabilize readings
}

No comments:

Post a Comment

MUD Three Mode operation Manual Automatic GPS

 Code for three mode operation: /*   3-Mode Headlight Controller   - Manual mode (driver uses a toggle to pick high/low)   - Auto mode (LDR...