I'm trying to make a VU meter inputting audio from my computer, analyzing it and then outputting it to LEDs. It sorta works...but it's as if it has a huge delay in it or something because when I stop the music, it takes about 10 seconds for the LEDs to gradually fade back down. I'd appreciate your input! Thanks. The code was modified from a PIC
int SoundLevel;
unsigned int Counter=0;
unsigned char BarGraph;
unsigned char i = 0;
unsigned int SoundMin = 1023;
unsigned int SoundMax = 0;
unsigned int SoundValue;
unsigned char j;
void setup()
{
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
}
void loop ()
{
SoundValue=analogRead(0);
//Since we are trying to measure amplitude, track the max and min values
if(SoundValue > SoundMax)
SoundMax = ((7*SoundMax) + SoundValue) >> 3;
//Here we are filtering the max value so it doesn't update too fast, and to discard
//the momentary spikes. The >> 3 is the same as /8, but faster
if(SoundValue < SoundMin)
SoundMin = ((7*SoundMin) + SoundValue) >> 3;
//Here we are filtering the min value so it doesn't update too fast and to discard
//the momentary dips. The >> 3 is the same as /8, but faster
SoundLevel = (SoundMax - SoundMin) - 98;
//Take the amplitude, minus a little, because there will be a little background noise
if(SoundLevel < 0) SoundLevel = 0;
//Calculate the number of bars to light up.
if(SoundLevel > 600)//If it's too big
BarGraph = 9; //just use the maximum 9 bars
else
BarGraph = SoundLevel / 60;
//Make the amplitude smaller by decreasing the max and increasing the min over time
//This will allow the displayed sound level to come back down, after a loud noise
if(Counter++ >= 4){
if(SoundMax > SoundMin) SoundMax--;
if(SoundMin < SoundMax) SoundMin++;
Counter = 0;
}//if
/*
A less code intensive method to do the following would be using port manipulation:
PORTD = B10101000; // sets digital pins 7,5,3 HIGH
PORTD maps to Arduino digital pins 0 to 7
PORTB maps to Arduino digital pins 8 to 13
http://www.arduino.cc/en/Reference/PortManipulation
To make the following code easier to follow/modify, I've used digitalWrite instead.
*/
if (BarGraph==1){
PORTD = B00000000;
PORTB = B00000000;
}
else if (BarGraph==2){
PORTD = B00000100;
PORTB = B00000000;
}
else if (BarGraph==3){
PORTD = B00001100;
PORTB = B00000000;
}
else if(BarGraph==4){
PORTD = B00011100;
PORTB = B00000000;
}
else if (BarGraph==5){
PORTD = B00111100;
PORTB = B00000000;
}
else if (BarGraph==6){
PORTD = B01111100;
PORTB = B00000000;
}
else if (BarGraph==7){
PORTD = B11111100;
PORTB = B00000000;
}
else if (BarGraph==8){
PORTD = B11111100;
PORTB = B00000001;
}
else if(BarGraph==9){
PORTD = B11111100;
PORTB = B00000011;
}
// Serial.print(BarGraph);
delay(10);
}//main