#include "FS.h" #include "SD.h" #include "SPI.h" const int sampleWindow = 1000; // Sample window width in mS (50 mS = 20Hz) unsigned int sample; unsigned int signalMax = 0; //minimum value unsigned int signalMin = 4096; //maximum value int db = 0; unsigned int seconds = 0; int sumTotal = 0; int sum10mins = 0; int average10mins = 0; int averageTotal = 0; int lowestReading = 2000; int highestReading = 0; void setup() { Serial.begin(115200); pinMode(32,INPUT); //check if the card is connected if(!SD.begin()){ Serial.println("Card Mount Failed"); return; } //opne the file and clear it and format it File data = SD.open("/data.txt", FILE_WRITE); File data10mins = SD.open("/data10mins.txt", FILE_WRITE); data.printf("Loudness(dB)\n"); data10mins.printf("AverageLoundness10mins(dB),AverageLoundnessTotal(dB),LowestLoundness(dB),HighestLoudness(dB)\n"); //save the file and close it data.close(); data10mins.close(); } void loop() { unsigned long startMillis= millis(); // Start of sample window float peakToPeak = 0; // peak-to-peak level // collect data for 50 mS while (millis() - startMillis < sampleWindow) { sample = analogRead(32); //get reading from microphone if (sample < 2048) // toss out spurious readings { if (sample > signalMax) { signalMax = sample; // save just the max levels } else if (sample < signalMin) { signalMin = sample; // save just the min levels } } } peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude //maps the values to the decible scale db = map(peakToPeak,100,250,40,80); //open the files File data = SD.open("/data.txt",FILE_APPEND); File data10mins = SD.open("/data10mins.txt",FILE_APPEND); //print the value to serial monitor Serial.printf("%d\n",db); //print the value to the file data.printf("%d\n",db); //update the tracker variables seconds++; sumTotal += db; sum10mins += db; //saving the lowest value if(dbhighestReading){ highestReading = db; } if(seconds%600 == 0){ //calculates 10min average average10mins = sum10mins/600; //calculates total average averageTotal = sumTotal/seconds; //prints to the file data10mins.printf("%d,%d,%d,%d\n",average10mins,averageTotal,lowestReading,highestReading); //prints to the serial Serial.printf("%d,%d,%d,%d\n",average10mins,averageTotal,lowestReading,highestReading); //resets the values back to original sum10mins = 0; lowestReading = 2000; highestReading = 0; } //saving the file data.close(); data10mins.close(); //refreshes the max and min signalMax = 0; signalMin = 4095; }