int ledPin = 13;
int inputPin = 2;
int pirState = LOW;
int val = 0;
int pinSpeaker = 10;

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(pinSpeaker, OUTPUT);
}
void loop(){
  val = digitalRead(inputPin);
  if (val == HIGH){
    digitalWrite(ledPin, HIGH);
    playtone(300, 160);
    delay(150);
    if (pirState == LOW){
      pirState = HIGH;
    }
  }else{
    digitalWrite(ledPin, LOW);
    playtone(0,0);
    delay(300);
    if(pirState == HIGH){
      Serial.println("Motion Ended");
      pirState = LOW;
    }
  }
}

void playtone (long duration, int freg){
  duration *=1000;
  int period = (1.0/freg) * 1000000;
  long elapsed_time = 0;
  while (elapsed_time < duration){
    digitalWrite(pinSpeaker, HIGH);
    delayMicroseconds(period/2);
    digitalWrite(pinSpeaker, LOW);
    delayMicroseconds(period/2);
    elapsed_time += (period);
  }
}