Devices & Components
Arduino Nano
Rotary Potentiometer, 10 kohm
5V 2.5A Switching Power Supply
Resistor 10k ohm
GP1287 VFD display 256x50
Capacitor 10 µF
Hardware & Tools
Soldering Station
Solder Soldering Wire
Software & Tools
Arduino IDE
Project description
Code
code
cpp
arduino code
1#include "U8g2lib.h" 2#include "fix_fft.h" 3#include <SPI.h> 4int buttonPin = 2; 5int oldButtonVal = 0; 6// u8g2 set up, bar, line position L & R 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, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); 15//U8GLIB_ST7920_128X64_1X lcd(EN, RW, CS); // serial use, PSB = GND 16 17char im[SAMPLES]; 18char data[SAMPLES]; 19int barht[SAMPLES]; 20int nPatterns = 2; 21int lightPattern = 1; 22void setup() 23{ 24 u8g2.begin(); // inti u8g2 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 // get audio data 36 for(i = 0; i < SAMPLES; i++) 37 { 38 val = analogRead(AUDIO)* 50; // 0-1023 39 data[i] = (char)(val/4 - 128); // store as char 40 im[i] = 0; // init all as 0 41 } 42 43 44 // run FFT 45 fix_fft(data, im, 7, 0); 46 47 // extract absolute value of data only, for 64 results 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 // u8g2 barchart 59 barchart(SAMPLES/4, barht); // plot SAMPLES / 4 = 32 as barchart gen cannot handle 128 bars 60} 61 62// plot line and bar at position and height 63void barchart(int n, int bh[]) 64{ 65 int i, s, w; // bars, spacing and width 66 67 s = (LINEXR - LINEXL) / n; 68 int buttonVal = digitalRead(buttonPin); 69 if (buttonVal == LOW && oldButtonVal == HIGH) {// button has just been pressed 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); // u8glib doesn't accept box height of 0 98 } 99 100 }while(u8g2.nextPage()); 101}
Documentation
Schematic
....
Schematic.jpg

Comments
Only logged in users can leave comments