Sei sulla pagina 1di 6

MICROPROCESSOR

EXPERIMENT NO. 16 : Sound Sensor Module


Connection:

Coding:
void initialize();
void runDetector();
boolean clapDetected();
int detectClaps(int numClaps);
void readMic();
void printStats();
int TOTAL_CLAPS_TO_DETECT = 3;
int offset = 80;
int CLAP_TIME=1000;
int sensorValue = 0;
int toggleOutput = -1;
int SIZE = 3;
int buffer[3];
int loopIteration = 0;
int average = 0;
int total = 0;
const int inPin0 = A0;
const int FINAL_DETECTED = 0, LOST_CONTINUITY = 1, CLAP_NOT_DETECTED = 2;
MICROPROCESSOR

void setup() {
Serial.begin(9600);
}
void loop() {
initialize();
runDetector();
}
void initialize()
{
loopIteration = 0;
total = 0;
average =0;
for(int i = 0; i < SIZE; i++)
{
readMic();
buffer[i] = sensorValue;
total = total + sensorValue;
average = (total/(i+1));
Serial.print("INIT - AVE: ");
Serial.print(average);
Serial.print(" Total: ");
Serial.print(total);
Serial.print(" Sensor: ");
Serial.print(sensorValue);
Serial.print(" Change: ");
Serial.println(sensorValue-average);
delay(50);
MICROPROCESSOR

}
}
void runDetector()
{
while(true)
{
int clapState = detectClaps(TOTAL_CLAPS_TO_DETECT);
if(clapState == FINAL_DETECTED || clapState == LOST_CONTINUITY)
{
Serial.println("--done--");
}
}
}
int detectClaps(int numClaps)
{
int clapNum = numClaps;
if(clapNum == 0)
{
toggleOutput *= -1;
Serial.println("----- Clap Limit Reached -----");
return FINAL_DETECTED;
}
readMic();
total = (total - buffer[loopIteration]) + sensorValue;
average = (total/SIZE);
buffer[loopIteration] = sensorValue;
loopIteration = (loopIteration+1)%SIZE;
MICROPROCESSOR

if(clapDetected())
{
Serial.print("detectClaps - Claps:");
Serial.println(TOTAL_CLAPS_TO_DETECT + 1 - numClaps);
printStats();
delay(100);
for(int i = 0; i < CLAP_TIME; i++)
{
int clapState = detectClaps(clapNum - 1);
if(clapState == FINAL_DETECTED || clapState == LOST_CONTINUITY)
{
return clapState;
}
}
return LOST_CONTINUITY;
}
return CLAP_NOT_DETECTED;
}
void printStats()
{
Serial.print("--- AVE: ");
Serial.print(average);
Serial.print(" Total: ");
Serial.print(total);
Serial.print(" iterNum: ");
Serial.print(loopIteration);
Serial.print(" Sensor: ");
MICROPROCESSOR

Serial.print(sensorValue);
Serial.print(" Change: ");
Serial.println(sensorValue-average);
}
boolean clapDetected()
{
return sensorValue > average + offset;
}
void readMic()
{
sensorValue = analogRead(inPin0);
}
MICROPROCESSOR

Potrebbero piacerti anche