This code actually works. A PIR sensor is used to trigger start. The jaw movement isn't perfect, but is very close. I suppose if one used the FFT filter it could be even better. Works well enough as is for a Halloween prop. By the way, I installed my servo backwards. The jaw is open completely at 0 degrees and closed at 120. The map function took care of this.
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <Servo.h>
#define SDCARD_CS_PIN 10
#define SDCARD_MOSI_PIN 7
#define SDCARD_SCK_PIN 14
// GUItool: begin automatically generated code
AudioPlaySdWav playSdWav1; //xy=190,172
AudioMixer4 mixer1; //xy=408.99993896484375,81.33999633789062
AudioOutputI2S i2s1; //xy=411,157.00999450683594
AudioAnalyzePeak peak1; //xy=565.6600036621094,152.00999450683594
AudioConnection patchCord1(playSdWav1, 0, i2s1, 0);
AudioConnection patchCord3(playSdWav1, 1, i2s1, 1);
AudioConnection patchCord2(playSdWav1, 0, mixer1, 0);
AudioConnection patchCord4(playSdWav1, 1, mixer1, 1);
AudioConnection patchCord6(mixer1, peak1);
AudioControlSGTL5000 sgtl5000_1; //xy=212.32998657226562,109.33000183105469
// GUItool: end automatically generated code
Servo jawServo;
int pirPin = 3;
int servoPin = 4;
int pirState = LOW;
void setup() {
Serial.begin(115200);
AudioMemory(8);
// Comment these out if not using the audio adaptor board.
// This may wait forever if the SDA & SCL pins lack
// pullup resistors
sgtl5000_1.enable();
sgtl5000_1.volume(0.8);
SPI.setMOSI(SDCARD_MOSI_PIN);
SPI.setSCK(SDCARD_SCK_PIN);
if (!(SD.begin(SDCARD_CS_PIN))) {
// stop here, but print a message repetitively
while (1) {
Serial.println("Unable to access the SD card");
delay(500);
}
}
// put your setup code here, to run once:
pinMode(pirPin, INPUT);
jawServo.attach(servoPin);
jawServo.writeMicroseconds(2000);
// attachInterrupt(pirPin, onPirHigh, RISING);
}
void loop() {
int val = digitalRead(pirPin); // read input value
if (val == HIGH) { // check if the input is HIGH
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
pirState = HIGH;
playFile("SDTEST2.wav");
}
}
}
void onPirHigh() {
if(!playSdWav1.isPlaying()) {
}
}
void playFile(const char *filename)
{
Serial.println(filename);
playSdWav1.play(filename);
// A brief delay for the library read WAV info
delay(5);
// Simply wait for the file to finish playing.
while (playSdWav1.isPlaying()) {
Serial.println("playing");
if (peak1.available()) {
Serial.println("peak avaiable");
float monoPeak = peak1.read() * 100.0;
long pos = map((long)monoPeak, 0, 100, 2000, 992);
Serial.println(pos);
jawServo.writeMicroseconds(pos);
delay(15);
}
}
jawServo.writeMicroseconds(2000);
pirState = LOW;
Serial.println("");
}