Mapping analog inputs - not working as expected

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);
    }
  }             
}

If you want the LED to stay on some you should not dim all the way to 255. I think that instead of the range 255-50 (off to fairly bright) you intended the range 205-0 (dim to full bright).

Ah of course, thanks!

It's not just the LEDs that are dim today :astonished:

So Serial print the values from analogRead and map what are they? By the way what external hardware are you using.

Mark

I'm using a bog standard op-amp peak detector on the input and a nifty MOSFET driver circuit I found on YouTube. I've attached the schematics. Here's the video I got the driver idea from too: