WhistleDetector.ino 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. This example reads audio data from an Invensense's ICS43432 I2S microphone
  3. breakout board, and uses the input to detect whistling sounds at a particular
  4. frequency. When a whistle is detected, it's level is used to control the
  5. brightness of an LED
  6. Circuit:
  7. * Arduino/Genuino Zero, MKRZero or MKR1000 board
  8. * ICS43432:
  9. * GND connected GND
  10. * 3.3V connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
  11. * WS connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
  12. * CLK connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
  13. * SD connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)
  14. created 30 November 2016
  15. by Sandeep Mistry
  16. */
  17. #include <ArduinoSound.h>
  18. // the LED pin to use as output
  19. const int ledPin = LED_BUILTIN;
  20. // sample rate for the input
  21. const int sampleRate = 8000;
  22. // size of the FFT to compute
  23. const int fftSize = 128;
  24. // size of the spectrum output, half of FFT size
  25. const int spectrumSize = fftSize / 2;
  26. // frequency of whistle to detect
  27. const int whistleFrequency = 1250;
  28. // map whistle frequency to FFT bin
  29. const int whistleBin = (whistleFrequency * fftSize / sampleRate);
  30. // array to store spectrum output
  31. int spectrum[spectrumSize];
  32. // create an FFT analyzer to be used with the I2S input
  33. FFTAnalyzer fftAnalyzer(fftSize);
  34. void setup() {
  35. // setup the serial
  36. Serial.begin(9600);
  37. // configure the pin for output mode
  38. pinMode(ledPin, OUTPUT);
  39. // setup the I2S audio input for the sample rate with 32-bits per sample
  40. if (!AudioInI2S.begin(sampleRate, 32)) {
  41. Serial.println("Failed to initialize I2S input!");
  42. while (1); // do nothing
  43. }
  44. // configure the I2S input as the input for the FFT analyzer
  45. if (!fftAnalyzer.input(AudioInI2S)) {
  46. Serial.println("Failed to set FFT analyzer input!");
  47. while (1); // do nothing
  48. }
  49. }
  50. void loop() {
  51. if (fftAnalyzer.available()) {
  52. // analysis available, read in the spectrum
  53. fftAnalyzer.read(spectrum, spectrumSize);
  54. // map the value of the whistle bin magnitude between 0 and 255
  55. int ledValue = map(spectrum[whistleBin], 50000, 60000, 0, 255);
  56. // cap the values
  57. if (ledValue < 0) {
  58. ledValue = 0;
  59. } else if (ledValue > 255) {
  60. ledValue = 255;
  61. }
  62. // set LED brightness based on whistle bin magnitude
  63. analogWrite(ledPin, ledValue);
  64. }
  65. }