// Beat Detection using analogRead for Low Frequencies
// Analog pin where the microphone is connected
const int micPin = A1;
const int LED = 13;
// Variables for beat detection
int rawSignal; // Variable to hold the incoming signal
float filteredSignal = 50; // Smoothed signal after applying low-pass filter
float previousFilteredSignal = 0;
float alpha = 0.10; // Smoothing factor for low-pass filter (0 < alpha < 1)
int threshold = 50; // Threshold value for beat detection (after filtering)
int beatCounter = 0; // Counter for the number of beats detected
unsigned long lastBeatTime = 0; // Time of the last detected beat
// Constants
const int sampleWindow = 10; // Sample window width in ms (10 ms)
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set micPin as input
pinMode(micPin, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
unsigned long startMillis = millis(); // Start of sample window
int peakToPeak = 0; // peak-to-peak measurement
int signalMax = 0;
int signalMin = 1024;
// Collect data for sampleWindow
while (millis() - startMillis < sampleWindow) {
rawSignal = analogRead(micPin);
// Apply low-pass filter
filteredSignal = alpha * rawSignal + (1 - alpha) * filteredSignal;
if (filteredSignal < 1024) { // Avoiding overflow
if (filteredSignal > signalMax) {
signalMax = filteredSignal; // Save just the max levels
}
if (filteredSignal < signalMin) {
signalMin = filteredSignal; // Save just the min levels
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
// Print the peak-to-peak value for debugging
Serial.println(peakToPeak);
// Check if a beat is detected
if (peakToPeak > threshold) {
// Ensure at least 300ms between beats (for debounce)
if (millis() - lastBeatTime > 200) {
beatCounter++;
digitalWrite(LED, HIGH);
lastBeatTime = millis();
// Print the beat count for debugging
Serial.print("Beat detected! Count: ");
Serial.println(beatCounter);
}
}
else
digitalWrite(LED, LOW);
}