| 1 | // Speaker demo for Circuit Playground -- when tapped, plays a very short |
|---|
| 2 | // digitized sound sample, very quietly (because teeny tiny speaker). |
|---|
| 3 | |
|---|
| 4 | #include <Adafruit_CircuitPlayground.h> |
|---|
| 5 | #include <Wire.h> |
|---|
| 6 | #include <SPI.h> |
|---|
| 7 | |
|---|
| 8 | // Enable ONE of these lines to pick a sound to play back when tapped: |
|---|
| 9 | #include "coin.h" // Super Mario coin sound |
|---|
| 10 | //#include "trek.h" // Star Trek TNG communicator noise |
|---|
| 11 | |
|---|
| 12 | volatile boolean play = false; |
|---|
| 13 | |
|---|
| 14 | // This function will be called automatically when a tap is detected by the |
|---|
| 15 | // accelerometer. This just sets the global flag 'play' to true, which is |
|---|
| 16 | // then detected in loop() (where the sound is then played)...doing heavy |
|---|
| 17 | // processing within an interrupt function is sometimes considered poor form. |
|---|
| 18 | void myFunction() { |
|---|
| 19 | play = true; // Hey loop(), play the sound! |
|---|
| 20 | } |
|---|
| 21 | |
|---|
| 22 | void setup() { |
|---|
| 23 | CircuitPlayground.begin(); |
|---|
| 24 | |
|---|
| 25 | // Configure accelerometer for +-4G range, use the tap interrupt |
|---|
| 26 | // feature to call myFunction() automatically when tapped. |
|---|
| 27 | CircuitPlayground.setAccelRange(LIS3DH_RANGE_4_G); |
|---|
| 28 | CircuitPlayground.setAccelTap(1, 127); |
|---|
| 29 | attachInterrupt(digitalPinToInterrupt(CPLAY_LIS3DH_INTERRUPT), myFunction, RISING); |
|---|
| 30 | } |
|---|
| 31 | |
|---|
| 32 | void loop() { |
|---|
| 33 | while(!play); // Wait for tap interrupt |
|---|
| 34 | |
|---|
| 35 | // Play sound data in the audio[] array (declared in one of the .h files). |
|---|
| 36 | // This function "blocks" -- that is, program flow stops until sound is |
|---|
| 37 | // done playing -- it does not play in the background. |
|---|
| 38 | CircuitPlayground.speaker.playSound(audio, sizeof(audio), SAMPLE_RATE); |
|---|
| 39 | |
|---|
| 40 | // Calling speaker.end() after playing a sound is optional -- this will |
|---|
| 41 | // turn off the pin 13 LED (it's connected to a microcontroller pin that's |
|---|
| 42 | // also related to the speaker), but there's a small audible click when it |
|---|
| 43 | // turns off. Tradeoffs! |
|---|
| 44 | CircuitPlayground.speaker.end(); |
|---|
| 45 | |
|---|
| 46 | play = false; // Clear flag, wait for interrupt |
|---|
| 47 | } |
|---|