#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <arduinoFFT.h>
#define AUDIO_IN 16
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define SAMPLES 64 // Number of samples to take for FFT
#define BANDS 15 // Number of frequency bands
#define BAR_HEIGHT 64 //53 pixel
arduinoFFT FFT = arduinoFFT();
double vReal[SAMPLES];
double vImag[SAMPLES];
byte audio_bar_height[15]; // sizes for the individual bars
byte audio_bar_peak[15]; // positions for the individual peaks (lines over the bars)
float heightAdjust = 0.3;
void setup() {
randomSeed(analogRead(0));
Serial.begin(115200);
Wire.begin(33, 35);
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.fillScreen(0);
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.cp437(true);
}
void loop() {
for (int i = 0; i < SAMPLES; i++) {
vReal[i] = random(1024);// analogRead(AUDIO_IN);
vImag[i] = 0;
}
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
display.clearDisplay();
for (int i = 0; i < BANDS; i++) {
int bandStart = (i * SAMPLES) / BANDS;
int bandEnd = ((i + 1) * SAMPLES) / BANDS;
double sum = 0;
for (int j = bandStart; j < bandEnd; j++) {
sum += vReal[j];
}
int averageMagnitude = sum / (bandEnd - bandStart+1)*heightAdjust;
audio_bar_height[i] = map(averageMagnitude, 0, 1023, 0, BAR_HEIGHT);
// Adjust the peak value with heightAdjust
//audio_bar_peak[i] = audio_bar_height[i];
// calculate the peak position
if (audio_bar_peak[i] < audio_bar_height[i]) {
audio_bar_peak[i] = audio_bar_height[i];
} else if (audio_bar_peak[i] > audio_bar_height[i]) {
audio_bar_peak[i]--; // slowly move the peak down, one pixel every frame
display.drawFastHLine(5 + i * 8, BAR_HEIGHT - audio_bar_peak[i], 5, SSD1306_WHITE); // draw peak
}
display.fillRect(5 + i * 8, BAR_HEIGHT - audio_bar_height[i], 5, audio_bar_height[i], SSD1306_WHITE); // draw bar
}
display.display();
}
Loading
wemos-s2-mini
wemos-s2-mini