]> git.piffa.net Git - arduino/blob - books/ArduinoNextSteps-master/ArduinoNextSteps/sketch_13_07_FFT_Freq/sketch_13_07_FFT_Freq.ino
first commit
[arduino] / books / ArduinoNextSteps-master / ArduinoNextSteps / sketch_13_07_FFT_Freq / sketch_13_07_FFT_Freq.ino
1 // sketch_13_07_FFT_Freq
2
3 #include "fix_fft.h"
4
5 const int analogPin = A0;
6 const long GAIN = 2;
7 char im[128];
8 char data[128];
9
10 const byte PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
11 const byte PS_16 = (1 << ADPS2);
12
13
14 void setup()
15 {
16   Serial.begin(9600);
17   ADCSRA &= ~PS_128;  // remove prescale of 128
18   ADCSRA |= PS_16;    // add prescale of 16 (1MHz)
19 }
20
21 void loop()
22 {
23   sampleWindowFull();
24   fix_fft(data, im, 7, 0);
25   updateData();
26
27   Serial.println(findF());
28 }
29
30 void sampleWindowFull()
31 {
32   for (int i = 0; i < 128; i++)
33   {                               
34     int val = (analogRead(analogPin) - 512) * GAIN;                       
35     data[i] = val / 4;               
36     im[i] = 0;     
37   }
38 }
39
40 void updateData()
41 {
42   for (int i = 0; i < 64; i++)
43   {
44     data[i] = sqrt(data[i] * data[i] + im[i] * im[i]); 
45   }
46 }
47
48 int findF()
49 {
50   int maxValue = 0;
51   int maxIndex = 0;
52   for (int i = 1; i < 64; i++)
53   {
54     int p = data[i];
55     if (p > maxValue)
56     {
57       maxValue = p;
58       maxIndex = i;
59     }
60   }
61   int f = maxIndex * 240;
62   return f;
63 }