Hi there
I'm trying to dim an LED using an audio input. The audio input is working fine, but I'm having trouble getting the input to scale properly to the desired output range.
The desired effect is that the LEDs remain on but dim when there is no sound, and then brighten in time to the music. They are reacting to the music, but they don't stay on, they just fade off. Here's my code, can anyone help me spot the problem? The output has to be inverted because I'm driving the LEDs with an N channel MOSFET, so the output is inverted.
const byte analogInPin = A0;
const byte analogOutPin = 3;
int smoothed; //variable to store filtered inpout
int currentBright = 50;
int targetBright;
int fadeDelay = 10000; //fading time in microseconds
void setup() {
}
void loop() {
smoothed = analogRead(analogInPin);
targetBright = map(smoothed, 0, 1023, 255, 50); //this line doesn't work - why?
// This section fades between one value and another to soften sudden changes in brightness
if (targetBright > currentBright) { // If the target brightness is brighter than the LED currently is then increase the brightness every so many microseconds
while(currentBright < targetBright){
currentBright++;
analogWrite(analogOutPin, currentBright);
delayMicroseconds(fadeDelay);
}
}
if (targetBright < currentBright) {
while(currentBright > targetBright){
currentBright--;
analogWrite(analogOutPin, currentBright);
delayMicroseconds(fadeDelay);
}
}
}

