Paso 6: Programa Contoller
Uso el debajo de código para programar el controlador. Asegúrese de que el número correcto de mics y cambiar las clavijas a cualquiera que utilizó para realizar las conexiones.
const int numReadings = 10;const int numberOfMics = 3; const int ambient = 600;
int index = 0; int maxMic = 0; boolean soundDetected = false;
int soundSensorPins[numberOfMics] = {A0, A1, A2}; int soundLEDPins[numberOfMics] = {3, 5, 7};
int soundArray[numberOfMics][numReadings]; int micTotals[numberOfMics]; boolean lightState[numberOfMics];
void setup() { Serial.begin(9600); // set LED pins to output for (int thisLED = 0; thisLED < numberOfMics; thisLED ++) { pinMode(soundLEDPins[thisLED], OUTPUT); } // init soundArray for (int thisReading = 0; thisReading < numReadings; thisReading++) { for (int thisMic = 0; thisMic < numberOfMics; thisMic++) { soundArray[thisMic][thisReading] = 0; } } // init micTotals for (int thisTotal = 0; thisTotal < numberOfMics; thisTotal ++) { micTotals[thisTotal] = 0; } // init lightState for (int thisState = 0; thisState < numberOfMics; thisState ++) { lightState[thisState] = false; } }
void loop() { // smooth reading for (int thisMic = 0; thisMic < numberOfMics; thisMic ++) { // remove last value micTotals[thisMic] = micTotals[thisMic] - soundArray[thisMic][index]; // read new value soundArray[thisMic][index] = analogRead(soundSensorPins[thisMic]); // get new total micTotals[thisMic] = micTotals[thisMic] + soundArray[thisMic][index]; } // check for a mic above threshold soundDetected = false; for (int thisMic = 0; thisMic < numberOfMics; thisMic++) { if (micTotals[thisMic] / numReadings > ambient) { soundDetected = true; Serial.println("Sound Detected"); } } // compare mics if (soundDetected == true) { maxMic = 0; for (int thisMic = 0; thisMic < numberOfMics; thisMic++) { if (micTotals[thisMic] > micTotals[maxMic]) { maxMic = thisMic; Serial.println(maxMic); } else { Serial.println(maxMic); } } for (int thisMic = 0; thisMic < numberOfMics; thisMic++) { if (thisMic == maxMic) { lightState[thisMic] = true; //Serial.println(thisMic); } else { lightState[thisMic] = false; } } } else { for (int thisMic = 0; thisMic < numberOfMics; thisMic++) { lightState[thisMic] = false; } } // advance to the next position in the array index = index + 1; // reset array if (index >= numReadings) { index = 0; } // set LEDs for (int thisLight = 0; thisLight < numberOfMics; thisLight++) { if (lightState[thisLight] == true) { digitalWrite(soundLEDPins[thisLight], HIGH); } else { digitalWrite(soundLEDPins[thisLight], LOW); } } delay(1); }