I'm trying to make an audio spectrum analyzer using 2 arduino UNO's and an RGB LED Matrix. The first arduino takes in an analog audio signal and runs it through a DFT algorithm. The second arduino gets the DFT output from the first arduino using I2C and visualizes the data on the LED matrix.
Sender code:
#include <Wire.h>
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
void setup()
{
Wire.begin();
Serial.begin(115200);
sbi(ADCSRA, ADPS2);
cbi(ADCSRA, ADPS1);
cbi(ADCSRA, ADPS0);
}
void loop()
{
int N=512;
int x[N];
long t, t0, k, k0;
int j=0;
float X_Ret, X_Imt, X_Re, X_Im,X_Mag;
float wrt[32];
//t0 = micros();
byte randData[32];
byte outData[32];
for(int i=0 ; i<32 ; i++){
if(i<10){
randData[i] = random(0,4);
}
else if(i<20){
randData[i] = random(0,10);
}
else{
randData[i] = random(0,16);
}
}
for(int i=0 ; i<N ; i++){
x[i] = analogRead(0)-512;
//delayMicroseconds(29);
}
//t = micros()-t0;
/*Serial.print("Time per sample: ");
Serial.println((float)t/N);
Serial.print("Frequency: ");
Serial.println((float)N*1000000/t);*/
t0 = micros();
//DFT start
for(int m=1 ; m<255 ; m+=8){
X_Re=0;
X_Im=0;
for(int n=0 ; n<N ; n++){
X_Ret=x[n]*(cos(6.28*m*n/N));
X_Imt=x[n]*(sin(6.28*m*n/N));
X_Re = X_Re + X_Ret;
X_Im = X_Im - X_Imt;
}
wrt[j]=sqrt(X_Re*X_Re+X_Im*X_Im);
if(wrt[j]>3200){
wrt[j]=3200;
}
outData[j]=round(wrt[j]*15/3200);
j++;
}
//DFT end
t = micros()-t0;
Serial.println(t);
Wire.beginTransmission(8);
Wire.write(randData,32);
Wire.endTransmission();
/*t = micros()-t0;
Serial.println(t);*/
//delay(1000);
}
Receiver code:
#include <Adafruit_GFX.h>
#include <RGBmatrixPanel.h>
#include <Wire.h>
#define CLK 8
#define LAT A3
#define OE 9
#define A A0
#define B A1
#define C A2
RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);
void setup() {
matrix.begin();
Serial.begin(9600);
Wire.begin(8);
Wire.onReceive(receiveEvent);
}
void loop() {
}
void receiveEvent(int howMany) {
int i=0;
uint8_t x,y;
int h[32];
while (0 < Wire.available()) {
h[i] = Wire.read();
i++;
}
matrix.fillScreen(0);
for(x=0;x<32;x++){
for(y=0;y<=h[x];y++){
matrix.drawPixel(x, y, matrix.Color333(7, 0, 0));
}
}
matrix.swapBuffers(false);
}
If you run this code everything works fine. I've printed the time the DFT algorithm takes to the serial monitor and it takes about 4 microseconds. However I'm just sending a randomly generated dataset called 'randData' to the second arduino. What i really want to send to the second arduino is 'outData', but when i change Wire.write(randData,32); to Wire.write(outData,32); the DFT algorithm now takes almost 5 seconds to run which is way to long to have a decent refresh rate on my LED matrix.
If you want to test this you don't need to have a second arduino with LED matrix attached to it. Just run the sender code on a standalone arduino and check the time the DFT algorithm takes with the serial monitor.