//all pin numbers
const int trigPin = 7;
const int echoPin = 6;
int buzzer = 5;
int redPin = 11;
int bluePin = 10;
int greenPin = 9;
int switchPin = 0; 
int switchState = LOW;
int onOffLight = 1;

void setup() {
  pinMode(buzzer, OUTPUT);
  pinMode(redPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(switchPin, INPUT);
  pinMode(onOffLight, OUTPUT);
  pinMode(A0, INPUT);

}

void setColour(int red, int green, int blue)
{
  analogWrite(redPin, red);
  analogWrite(bluePin, blue);
  analogWrite(greenPin, green);
}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

void alarm(int speed){ //function for alarm 
  if(switchState == HIGH){ //alarm only works if switch is on
  	tone(5,220,100); //speed is how many miliseconds between two rings
  	delay(speed);
  	tone(5,180,100);
  	delay(speed);
    digitalWrite(onOffLight, HIGH);//if alarm is on than the LED is on
  }
  else
    digitalWrite(onOffLight, LOW);//if alarm is off than led is off
}

void loop()
{
  long duration, inches;
  switchState = digitalRead(switchPin);//reading the pin state each loop

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  inches = microsecondsToInches(duration);
 
  delay(100);
  setColour(0,0,0); //reseting RGB led each time
  
  //3 tiers of distance to sensor
  //each tier closer makes colour change
  //and alarm gets faster
  if (inches <=35 & analogRead(A0)> 500){
    setColour(255,0,0);//red
    alarm(300);
  }
  else if (inches <=80 & analogRead(A0)> 500){
    setColour(255,255,0);//yellow
    alarm(400);
  }
  else if (analogRead(A0)> 500){
    setColour(0,255,0);//green
    alarm(700);
  }

}