81 lines
1.9KB

  1. /* Play a flute sound when a button is pressed.
  2. Connect a pushbutton to pin 1 and pots to pins A2 & A3.
  3. The audio tutorial kit is the intended hardware:
  4. https://www.pjrc.com/store/audio_tutorial_kit.html
  5. Without pots connected, this program will play a very
  6. strange sound due to rapid random fluctuation of the
  7. pitch and volume!
  8. Requires Teensy 3.2 or higher.
  9. Requires Audio Shield: https://www.pjrc.com/store/teensy3_audio.html
  10. */
  11. #include <Bounce.h>
  12. #include <Audio.h>
  13. #include <Wire.h>
  14. #include <SPI.h>
  15. #include <SD.h>
  16. #include <SerialFlash.h>
  17. #include "BasicFlute1_samples.h"
  18. AudioSynthWavetable wavetable;
  19. AudioOutputI2S i2s1;
  20. AudioMixer4 mixer;
  21. AudioConnection patchCord1(wavetable, 0, mixer, 0);
  22. AudioConnection patchCord2(mixer, 0, i2s1, 0);
  23. AudioConnection patchCord3(mixer, 0, i2s1, 1);
  24. AudioControlSGTL5000 sgtl5000_1;
  25. // Bounce objects to read pushbuttons
  26. Bounce button0 = Bounce(0, 15);
  27. Bounce button1 = Bounce(1, 15); // 15 ms debounce time
  28. Bounce button2 = Bounce(2, 15);
  29. void setup() {
  30. Serial.begin(115200);
  31. pinMode(0, INPUT_PULLUP);
  32. pinMode(1, INPUT_PULLUP);
  33. pinMode(2, INPUT_PULLUP);
  34. AudioMemory(20);
  35. sgtl5000_1.enable();
  36. sgtl5000_1.volume(0.8);
  37. mixer.gain(0, 0.7);
  38. wavetable.setInstrument(BasicFlute1);
  39. wavetable.amplitude(1);
  40. }
  41. bool playing = false;
  42. void loop() {
  43. // Update all the button objects
  44. button0.update();
  45. button1.update();
  46. button2.update();
  47. //Read knob values
  48. int knob1 = analogRead(A3);
  49. int knob2 = analogRead(A2);
  50. //Get frequency and gain from knobs
  51. float freq = (float)knob1/5.0;
  52. float gain = (float)knob2/1023.0;
  53. //Set a low-limit to the gain
  54. if (gain < .05) gain = .05;
  55. if (button1.fallingEdge()) {
  56. if (playing) {
  57. playing = false;
  58. wavetable.stop();
  59. }
  60. else {
  61. playing = true;
  62. wavetable.playFrequency(freq);
  63. wavetable.amplitude(gain);
  64. }
  65. }
  66. wavetable.amplitude(gain);
  67. wavetable.setFrequency(freq);
  68. }