1#include "U8g2lib.h"
2#include "fix_fft.h"
3#include <SPI.h>
4int buttonPin = 2;
5int oldButtonVal = 0;
6
7#define LINEY 40
8#define LINEXL 0
9#define LINEXR 256
10
11#define SAMPLES 128
12
13#define AUDIO A0
14 U8G2_GP1287AI_256X50_1_4W_SW_SPI u8g2(U8G2_R0, 13, 11, 10, 9, 8);
15
16
17char im[SAMPLES];
18char data[SAMPLES];
19int barht[SAMPLES];
20int nPatterns = 2;
21int lightPattern = 1;
22void setup()
23{
24 u8g2.begin();
25 u8g2.setContrast(25);
26 pinMode(2, INPUT_PULLUP);
27}
28
29void loop()
30{
31 static int i, j;
32 int val;
33
34
35
36 for(i = 0; i < SAMPLES; i++)
37 {
38 val = analogRead(AUDIO)* 50;
39 data[i] = (char)(val/4 - 128);
40 im[i] = 0;
41 }
42
43
44
45 fix_fft(data, im, 7, 0);
46
47
48 for(i = 0; i < SAMPLES/2; i++)
49 {
50 barht[i] = (int)sqrt(data[i] * data[i] + im[i] * im[i]);
51 }
52
53 for(i = 0, j = 0; i < SAMPLES/2; i++, j += 2)
54 {
55 barht[i] = barht[j] + barht[j + 1];
56 }
57
58
59 barchart(SAMPLES/4, barht);
60}
61
62
63void barchart(int n, int bh[])
64{
65 int i, s, w;
66
67 s = (LINEXR - LINEXL) / n;
68 int buttonVal = digitalRead(buttonPin);
69 if (buttonVal == LOW && oldButtonVal == HIGH) {
70 lightPattern = lightPattern + 1;
71 }
72 if (lightPattern > nPatterns) lightPattern = 1;
73 oldButtonVal = buttonVal;
74
75 switch(lightPattern) {
76 case 1:
77 w = s / 2;
78 break;
79 case 2:
80 w = s / 1;
81 }
82
83 u8g2.firstPage();
84 do
85 {
86 u8g2.setFont(u8g2_font_6x12_tf);
87 u8g2.drawStr(80, 7, "FFT Audio Spectrum");
88 u8g2.drawLine(LINEXL, LINEY, LINEXR, LINEY);
89 u8g2.drawStr(0, LINEY + 10, "0");
90 u8g2.drawStr(50, LINEY + 10, "1k");
91 u8g2.drawStr(110, LINEY + 10, "2k");
92 u8g2.drawStr(164, LINEY + 10, "3k");
93 u8g2.drawStr(220, LINEY + 10, "4k");
94 u8g2.drawStr(240, LINEY + 10, "Hz");
95 for(i = 0; i < n; i++)
96 {
97 u8g2.drawBox(LINEXL + s * i, LINEY - bh[i], w, bh[i] + 1);
98 }
99
100 }while(u8g2.nextPage());
101}