ClapDetector.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. This example reads audio data from an Invensense's ICS43432 I2S microphone
  3. breakout board, and uses the input to detect clapping sounds. An LED is
  4. togggled when a clapp is detected.
  5. Circuit:
  6. * Arduino/Genuino Zero, MKRZero or MKR1000 board
  7. * ICS43432:
  8. * GND connected GND
  9. * 3.3V connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
  10. * WS connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
  11. * CLK connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
  12. * SD connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)
  13. created 18 November 2016
  14. by Sandeep Mistry
  15. */
  16. #include <ArduinoSound.h>
  17. // the LED pin to use as output
  18. const int ledPin = LED_BUILTIN;
  19. // the amplitude threshold for a clap to be detected
  20. const int amplitudeDeltaThreshold = 100000000;
  21. // create an amplitude analyzer to be used with the I2S input
  22. AmplitudeAnalyzer amplitudeAnalyzer;
  23. // variable to keep track of last amplitude
  24. int lastAmplitude = 0;
  25. void setup() {
  26. // setup the serial
  27. Serial.begin(9600);
  28. // configure the LED pin as an output
  29. pinMode(ledPin, OUTPUT);
  30. // setup the I2S audio input for 44.1 kHz with 32-bits per sample
  31. if (!AudioInI2S.begin(44100, 32)) {
  32. Serial.println("Failed to initialize I2S input!");
  33. while (1); // do nothing
  34. }
  35. // configure the I2S input as the input for the amplitude analyzer
  36. if (!amplitudeAnalyzer.input(AudioInI2S)) {
  37. Serial.println("Failed to set amplitude analyzer input!");
  38. while (1); // do nothing
  39. }
  40. }
  41. void loop() {
  42. // check if a new analysis is available
  43. if (amplitudeAnalyzer.available()) {
  44. // read the new amplitude
  45. int amplitude = amplitudeAnalyzer.read();
  46. // find the difference between the new amplitude and the last
  47. int delta = amplitude - lastAmplitude;
  48. // check if the difference is larger than the threshold
  49. if (delta > amplitudeDeltaThreshold) {
  50. // a clap was detected
  51. Serial.println("clap detected");
  52. // toggle the LED
  53. digitalWrite(ledPin, !digitalRead(ledPin));
  54. // delay a bit to debounce
  55. delay(100);
  56. }
  57. // update the last amplitude with the new amplitude
  58. lastAmplitude = amplitude;
  59. }
  60. }