Controlling a LCD backlight

Hi,
I'm in the process of adding backlight for the LCD on my RC-transmitter and had a spare Nano, so I decided to go overkill on the control of it.
I have a input from the buzzer on the transmitter, (via a optocoupler)
and the plan was to light the backlight everytime it sounded, and after a couple of seconds it would fade to a lower light then turn completely off after a few more seconds.

after some tweeking of my second attempt, I got it to actually turn off, but the problem I have is that I want the light to stay on for 4 seconds after the LAST beep, now it is on for 4 (+8 at dim) seconds after the FIRST beep.

Can someone please help me?

Here is the code:

const int buzzerPin = 2;     // Signal from buzzer
const int ledPin =  11;      // Backlight

int buzzerState = 0;

void light(int state){

 switch (state){
 case 1: // full / half brightness
 {
    analogWrite(ledPin, 255); // full brightness on backlight
    delay(4000);
    analogWrite(ledPin, 200); // reduced brightness on backlight
    delay(8000);
 }
 case 2: // turn off light
 {
    digitalWrite(ledPin, 0); // turn backlight off:
 }
 }
 }

void setup() {
  pinMode(ledPin, OUTPUT);      
  pinMode(buzzerPin, INPUT);     
}

void loop(){
  // read the state of the buzzer value:
  buzzerState = digitalRead(buzzerPin);

  // check if the buzzer is sounded.
  // if it is, the buzzerState is HIGH:
  if (buzzerState == HIGH) {        
    light(1);
    } 
  else {
    light(2);

  }
}

THANKS!

That made me think in a new way, and solved the problem, also tidied the code up a bit. :slight_smile:

const int buzzerPin = 2; // Signal from buzzer
const int ledPin = 11; // Backlight

int buzzerState = 0;
long previousMillis = 0;
long full = 8000; //time in ms for full brightness
long dim = 12000; /time in ms for dimmed brightness

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, INPUT);
}

void loop(){

buzzerState = digitalRead(buzzerPin); // read the state of the buzzer:

unsigned long currentMillis = millis();
// check if the buzzer is sounded.
// if it is, the buzzerState is HIGH:
if(buzzerState == HIGH) {
previousMillis = currentMillis;
}
if(currentMillis - previousMillis < full)
analogWrite(ledPin, 255);

else if(currentMillis - previousMillis < full + dim)
analogWrite(ledPin, 200);

else
analogWrite(ledPin, 0);

}