Press button to regulate buzzer

Hello,

I have a question about my arduino project. First let me explain my setup: 1 potentiometer with a threshold value of 511. If the threshold value is below 511, one green led will be on. If the threshold is becomes above 511, the green led will fade off, 1 red led will fade on and a buzzer will make a noise and vice versa.

The next thing a want to reach is implementing a button to shut off the buzzer when pressed, but the red led will still have to be on.

So to put this into schematic order:

  • Threshold <511 the buzzer is off, green led on red led off.
  • Threshold >511 buzzer on, green led fade out, red led fade on.
  • When button pressed buzzer of until threshold <511, red led still on

Does someone has any tips on how to reach my goal?

Code:

int brightness = 0;
int brightness2 = 255;
int buzzer = 4;
int threshold = 0;
void setup()
{
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(4, OUTPUT);
pinMode(A0, INPUT);
pinMode(2, INPUT);
Serial.begin(9600);
}

void loop()
{
threshold = analogRead(A0);
Serial.println(threshold);

if (threshold>511 && brightness < 255) {
brightness += 5;
brightness2 -= 5;
analogWrite(9, brightness);
analogWrite(8, brightness2);
delay(30);
}
else if (threshold<511 && brightness > 0) {
brightness -= 5;
brightness2 += 5;
analogWrite(9, brightness);
analogWrite(8, brightness2);
delay(30);
}
if (threshold>511) {
tone(buzzer, 1000, 2000);
}
else
noTone(buzzer);
}

See my comments below:

int brightness = 0;
int brightness2 = 255;
int buzzer = 4;
int threshold = 0;
bool mute = false;
void setup()
{
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(A0, INPUT);
  pinMode(2, INPUT_PULLUP); // wire the button to ground and use internal pullup
  Serial.begin(9600);
}

void loop()
{
  threshold = analogRead(A0);
  Serial.println(threshold);
 
  if (threshold>511 && brightness < 255) {
      brightness += 5;
      brightness2 -= 5;
      analogWrite(9, brightness);
      analogWrite(8, brightness2);
      delay(30);
    }
else if (threshold<511 && brightness > 0) {
    brightness -= 5;
    brightness2 += 5;
    analogWrite(9, brightness);
    analogWrite(8, brightness2);
    delay(30);
  }

  if (threshold>511 && !mute) { // only sound the buzzer if its not muted
    tone(buzzer, 1000, 2000);
  }
  else
    noTone(buzzer);

  if (threshold>511 && digitalRead(2)==LOW) { // mute the buzzer if button is pressed while above threshold
    mute = true;
  }
  if (threshold<=511) { // reset mute if the value drops below threshold
    mute=false; 
  }
  
}
[\code]