#include #define TX 0 #define RX 1 #define soundSensor 2 SoftwareSerial mySerial(RX,TX); const char sampleTime =50; byte micOut; boolean state = true; void setup() { mySerial.begin(9600); } void loop(){ unsigned int micOutput = findPTPAmp(); mySerial.println(micOutput); /* if (micOutput>=150){ if(state){ mySerial.println("Led oN"); state= false; } else { mySerial.println("Led off"); state=true; } }*/ } int findPTPAmp(){ // Time variables to find the peak-to-peak amplitude unsigned long startTime= millis(); // Start of sample window unsigned int PTPAmp = 0; // Signal variables to find the peak-to-peak amplitude unsigned int maxAmp = 0; unsigned int minAmp = 1023; // Find the max and min of the mic output within the 50 ms timeframe while(millis() - startTime < sampleTime) { micOut = analogRead(soundSensor); if( micOut < 1023) //prevent erroneous readings { if (micOut > maxAmp) { maxAmp = micOut; //save only the max reading } else if (micOut < minAmp) { minAmp = micOut; //save only the min reading } } } PTPAmp = maxAmp - minAmp; // (max amp) - (min amp) = peak-to-peak amplitude //double micOut_Volts = (PTPAmp * 3.3) / 1024; // Convert ADC into voltage //Return the PTP amplitude. return PTPAmp; }