Hi guys, wondering if anyone can help me optimize this code. I'm using an Arduino UNO R3.
#define LOG_OUT 0 // use the log output function
#define FFT_N 256 // set to 256 point fft
#define LIN_OUT 1
#include <LedControl.h>
#include <FFT.h>
int DIN = 12;
int CS = 11;
int CLK = 10;
//int delayTime = 5;
float factors[8] = {1, 1.1, 1.35, 1.45, 1.55, 1.7, 1.9, 2.1}; //factors to increase the height of each column
unsigned char hs[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //height of each column
LedControl lc = LedControl(DIN, CLK, CS, 0);
void setup() {
lc.shutdown(0, false); //The MAX72XX is in power-saving mode on startup
lc.setIntensity(0, 0); // Set the brightness to maximum value
lc.clearDisplay(0); // and clear the display
TIMSK0 = 0; // turn off timer0 for lower jitter
ADCSRA = 0xe5; // set the adc to free running mode
ADMUX = 0x40; // use adc0
DIDR0 = 0x01; // turn off the digital input for adc0
Serial.begin(115200); // use the serial port
}
unsigned char borders[9] = {0, 15, 31, 47, 63, 79, 95, 111, 127}; //borders of the frequency areas
void setColumn(int column, unsigned char height) {
// maps height from 0 to 255 to 0 to 8
unsigned char h = (unsigned char) map(height, 0, 255, 0, 8);
// apply multipliers to heights
h = (unsigned char)(h * factors[column]);
// if less than 0,
if (h < hs[column]) {
// goes from 0 -> 255
hs[column]--;
} else if (h > hs[column]) {
hs[column] = h;
}
// light up LEDs
for (unsigned char y = 0; y < 8; y++) {
if (hs[column] > y) {
// addr then col then row
lc.setLed(0, column, y, true);
} else {
lc.setLed(0, column, y, false);
}
}
}
void loop() {
while (1) { // reduces jitter
cli(); // UDRE interrupt slows this way down on arduino1.0
for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
while (!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc
byte m = ADCL; // fetch adc data
byte j = ADCH;
int k = (j << 8) | m; // form into an int
k -= 0x0200; // form into a signed int
k <<= 6; // form into a 16b signed int
fft_input[i] = k; // put real data into even bins
fft_input[i + 1] = 0; // set odd bins to 0
}
fft_window(); // window the data for better frequency response
fft_reorder(); // reorder the data before doing the fft
fft_run(); // process the data in the fft
fft_mag_lin(); // take the output of the fft
sei();
// for each column
for (int i = 0; i < 8; i++) {
// find the maximum value within the specified frequency borders
int maxVal = 0;
for (int j = borders[i]; j < borders[i + 1]; j++) {
if ((unsigned char) fft_lin_out[j] > maxVal) {
maxVal = (unsigned char) fft_lin_out[j];
}
}
// determine height and light up LED
setColumn(i, maxVal);
Serial.println(maxVal);
}
}
}
Error message is:
Sketch uses 7718 bytes (23%) of program storage space. Maximum is 32256 bytes.
Global variables use 1606 bytes (78%) of dynamic memory, leaving 442 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.