Arduino FFT Library
Programming example
Here is an example Arduino sketch that shows the FFT library being used to obtain an 8b log magnitude output for 128 frequency bins. The data is taken in from the ADC. There is a Pure Data patch for visualising the data.
1 /*
2 fft_adc.pde
3 guest openmusiclabs.com 8.18.12
4 example sketch for testing the fft library.
5 it takes in data on ADC0 (Analog0) and processes them
6 with the fft. the data is sent out over the serial
7 port at 115.2kb. there is a pure data patch for
8 visualizing the data.
9 */
10
11 // do #defines BEFORE #includes
12 #define LOG_OUT 1 // use the log output function
13 #define FFT_N 256 // set to 256 point fft
14
15 #include <FFT.h> // include the library
16
17 void setup() {
18 Serial.begin(115200); // use the serial port
19 TIMSK0 = 0; // turn off timer0 for lower jitter - delay() and millis() killed
20 ADCSRA = 0xe5; // set the adc to free running mode
21 ADMUX = 0x40; // use adc0
22 DIDR0 = 0x01; // turn off the digital input for adc0
23 }
24
25 void loop() {
26 while(1) { // reduces jitter
27 cli(); // UDRE interrupt slows this way down on arduino1.0
28 for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
29 while(!(ADCSRA & 0x10)); // wait for adc to be ready
30 ADCSRA = 0xf5; // restart adc
31 byte m = ADCL; // fetch adc data
32 byte j = ADCH;
33 int k = (j << 8) | m; // form into an int
34 k -= 0x0200; // form into a signed int
35 k <<= 6; // form into a 16b signed int
36 fft_input[i] = k; // put real data into even bins
37 fft_input[i+1] = 0; // set odd bins to 0
38 }
39 // window data, then reorder, then run, then take output
40 fft_window(); // window the data for better frequency response
41 fft_reorder(); // reorder the data before doing the fft
42 fft_run(); // process the data in the fft
43 fft_mag_log(); // take the output of the fft
44 sei(); // turn interrupts back on
45 Serial.write(255); // send a start byte
46 Serial.write(fft_log_out, 128); // send out the data
47 }
48 }
49