Why does the potentiometer act as an on/off switch in my program? I'm using an HC-SRO4 Ultrasonic Sensor and a D10K Potentiometer. So, I was just messing around with the potentiometer in the program and then tried to change the brightness of the LED which turns on if a certain condition is met, but the potentiometer acts like an ON/OFF switch instead. I'd like to know why this happens and how can I change the LED's brightness normally in this situation. 

long duration;
int distance;
int trigPin = 9;
int echoPin = 10;
int buzzer = 11;
int LED = 3;
boolean detected = false;
#define pot 0
int val = 0;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(buzzer,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
val  = analogRead(pot);
val  = map(val, 0, 1023, 0, 255);
Serial.println  (distance);

if(distance &lt; 50 &amp;&amp; distance != 0){ // distance != 0  because sometimes the distance's first value is sometimes 0 which ruins the purpose of
 // the program
  analogWrite(LED, val);
  alarm();
  detected = true; 
}
else if(detected){ 
  digitalWrite(LED,LOW);
  alarm();
}
}

void alarm(){
  tone(buzzer, 450);
  delay(100);
  tone(buzzer, 1000);
  delay(100);
  }
The answer is very simple. You use pin 12 for LED. Pin 12 can't do analogWrite(). This pin doesn't support PWM on Arduino UNO (Atmega 328)

Pin 3 is not OK either. Use of tone() function disables PWM on pin 3. From reference: "Use of the tone() function will interfere with PWM output on pins 3 and 11".