I want to program a KY037 microphone to measure the ambient sound in dB and every mesaure it makes I will save it in a microSD, including the value of sound and the time in which it took it (this time I haven´t added yet)
I´ve used lots of codes so far but this is what I got now:
#include <SPI.h>
#include <SD.h>
File myFile;
int j;
float voltage, db;
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
#define SENSOR_PIN A0
#define CS_PIN 10
// Ejemplo de calibracion (ajustar valores segun mediciones reales)
const float vRef = 5.0; // Voltaje de referencia (valor de alimentación)
const float dbRef = 0.0; // dB a 0 volts (ajustar según micrófono)
const float dbPerVolt = 20.0; // dB por cada volt (ajustar según micrófono)
void setup() {
pinMode(SENSOR_PIN, INPUT_PULLUP); // Set the signal pin as input
pinMode(CS_PIN, OUTPUT);
Serial.begin(115200);
if (SD.begin()) {
Serial.println("SD card ready to use");
} else {
Serial.println("SD card not ready");
return;
}
}
void loop() {
myFile = SD.open("data.csv", FILE_WRITE);
unsigned long startMillis = millis(); // Start of sample window
double peakToPeak = 0; // peak-to-peak level
double signalMin = 1024; // maximum value
double signalMax = 0; // minimum value
// collect data for 50 ms
while ((millis() - startMillis) < sampleWindow) {
sample = analogRead(SENSOR_PIN); // get reading from microphone
voltage = sample * vRef / 1023.0; // convert reading to voltage
if (voltage > signalMax) {
signalMax = voltage; // save just the max levels
} else if (voltage < signalMin) {
signalMin = voltage; // save just the min levels
}
}
peakToPeak = signalMax - signalMin;
// Ejemplo de conversion a dB (ajustar segun calibracion real)
db = dbRef + dbPerVolt * peakToPeak;
// Write data to SD card
if (myFile) {
Serial.print("PeakToPeak:");
Serial.print(peakToPeak);
Serial.print(",");
Serial.print("Decibels:");
Serial.println(db);
myFile.print(String(db));
myFile.print(",");
myFile.print(String(millis() / 1000));
myFile.println();
myFile.close();
} else {
Serial.print("Error opening file.");
}
}
The problem with this is that with applause that sholud measure over 70-80 dB, it prints a value of 200 or maybe 400 dB.
New contributor
Mr. Buddy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.