...
Input Circuit
Sample Code
Size of band bin = Sampling Rate/#Samples
Code Block |
---|
|
#include <arduinoFFT.h>
#define AUDIO_IN_PIN A0
#define SAMPLES 128
#define SAMPLING_FREQ 3200
#define AMPLITUDE 100
#define NUM_BANDS 8
#define NOISE 500 // Used as a crude noise filter, values below this are ignored
unsigned int sampling_period_us;
double vReal[SAMPLES];
double vImag[SAMPLES];
int bandValues[] = {0,0,0,0,0,0,0,0};
unsigned long newTime;
arduinoFFT FFT = arduinoFFT(vReal, vImag, SAMPLES, SAMPLING_FREQ);
void setup() {
Serial.begin(115200);
Serial.println("Reading....");
sampling_period_us = round(1000000 * (1.0 / SAMPLING_FREQ));
//pinMode(AUDIO_IN_PIN,INPUT);
Serial.println("Reading....");
sampleInput();
}
void loop() {
}
void sampleInput() {
// Reset bandValues[]
for (int i = 0; i<NUM_BANDS; i++){
bandValues[i] = 0;
}
// Sample the audio pin
for (int i = 0; i < SAMPLES; i++) {
newTime = micros();
vReal[i] = analogRead(AUDIO_IN_PIN); // A conversion takes about 9.7uS on an ESP32
//Serial.print("analogVal: ");
//Serial.println(vReal[i]);
vImag[i] = 0;
while ((micros() - newTime) < sampling_period_us) { /* chill */ }
}
// Compute FFT
FFT.DCRemoval();
FFT.Windowing(FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(FFT_FORWARD);
FFT.ComplexToMagnitude();
// BandSizebinSize = SamplingRateSAMPLING_FREQ / NumberOfSamplesSAMPLES
// Bandsizebinsize = 3200/64128 = 50Hz25Hz
// Analyse FFT results
int fbiggestFrequency = 0;
int cmagnitude = 0;
int freqSizebinsize = SAMPLING_FREQ / SAMPLES;
// Don't use sample 0 and only first SAMPLES/2 are usable.
// Each array element represents a frequency bin and its value the amplitude.
for (int i = 21; i < (SAMPLES/2); i++){
if (vReal[i] > NOISE) { // Add a crude noise filter
Serial.print(i);
Serial.print("[");
Serial.print((i-1)*freqSizebinsize);
Serial.print("]");
Serial.print(": ");
Serial.println((int)vReal[i]);
if((int)vReal[i] > cmagnitude){
fbiggestFrequency=(i-1)*freqSizebinsize;
cmagnitude=(int)vReal[i];
}
}
}
if(c>0biggestFrequency>0){
Serial.print("f=");
Serial.print(fbiggestFrequency);
Serial.print(" c=");
Serial.println(cmagnitude);
}
} |
References