Code:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioInputI2S i2s; //xy=347,467
AudioMixer4 mixer; //xy=491,480
AudioAnalyzeFFT1024 fft1024; //xy=669,479
AudioConnection patchCord1(i2s, 0, mixer, 0);
AudioConnection patchCord2(i2s, 1, mixer, 1);
AudioConnection patchCord3(mixer, fft1024);
AudioControlSGTL5000 audioShield; //xy=366,225
// GUItool: end automatically generated code
//Needed FFT Bands are 1, 2, 3, 6, 12, 24, 47, 94, 187, 373.
//These represent the 10 bands i am attempting to read, which are
//32Hz, 64Hz, 125Hz, 250Hz, 500Hz, 1KHz, 2KHz, 4KHz, 8KHz & 16KHz.
//although they're slightly off because the FFT has a resolution of 43Hz, however it should be close enough to give
//usable data, if not i will have to modify the components the equalizer is comprised of.
const int addr = 16; //I2C communication address, device will work as slave.
const int myInput = AUDIO_INPUT_LINEIN; //Defines Audio Input pins for FFT function.
float levelF[10]; //array to hold the frequency band levels
int levelI[10];
void setup() {
AudioMemory(12); //Audio library requires memory to function properly.
//Enable the Audio Shield (SGTL5000) and select input
audioShield.enable();
audioShield.inputSelect(myInput);
//Mute Outputs, as we aren't using those.
audioShield.muteHeadphone();
audioShield.muteLineout();
//configure mixer to equally add left & right channels.
mixer.gain(0, 0.5);
mixer.gain(1, 0.5);
while(!Serial && millis() < 1000){} //wait for a Serial connection to start, timeout after 1000ms
Serial.println("Serial Start");
//Begin I2C
Wire1.begin(addr);
Wire1.onRequest(SendFFT);
}
void loop() {
if(fft1024.available()){
//The FFT library works linearly, but music works in octaves
//because of that, we read multiple bins for the higher frequencies,
//so we don't throw away useful data.
//NOTE TO SELF: Bins should be in order now. 24/03 kl.4:10 ... du skal virkelig have fikset hvornår du sover...
levelF[0] = fft1024.read(0);
levelF[1] = fft1024.read(1);
levelF[2] = fft1024.read(2, 4);
levelF[3] = fft1024.read(5, 8);
levelF[4] = fft1024.read(9, 17);
levelF[5] = fft1024.read(18, 35);
levelF[6] = fft1024.read(36, 72);
levelF[7] = fft1024.read(73, 140);
levelF[8] = fft1024.read(141, 280);
levelF[9] = fft1024.read(281, 511);
for(int i = 0; i > 9; i++){
levelF[i] = levelF[i] + 0.5;
levelI[i] = (int) levelF[i];
}
}
//Serielt Output for at tjekke FFT værdier
for(int j = 0; j > 9; j++){
Serial.print("Band ");
Serial.print(j);
Serial.print(": ");
Serial.println(levelF[j]);
}
}
//When the I2C Master (the Touch Display) requests updated values, send them over.
void SendFFT() {
Serial.println("I2C Requested");
for(int i = 0; i > 9; i++){
Wire1.write(levelI[i]);
}
Serial.println("I2C Sent");
}