Advertisement
SimoneR2

PIR SENSOR

Sep 20th, 2015
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. /*-----------------------*
  2.  * Made by coolyyz154    *
  3.  *-----------------------*/
  4. int ledPin = 10; // choose the pin for the LED
  5. int inputPin = 2; // choose the input pin (for PIR sensor)
  6. int pirState = LOW; // we start, assuming no motion detected
  7. int val = 0; // variable for reading the pin status
  8. int pinSpeaker = 13; //Set up a speaker on a PWM pin (digital 9, 10, or 11)
  9.  
  10. void setup() {
  11.   pinMode(ledPin, OUTPUT); // declare LED as output
  12.   pinMode(pinSpeaker, OUTPUT); //declare speaker pin as output
  13.   pinMode(inputPin, INPUT); // declare sensor as input
  14.   Serial.begin(9600); //start serial communication at 9600 baud
  15. }
  16.  
  17. void loop() {
  18.   val = digitalRead(inputPin); // read input value
  19.   if (val == HIGH) { // check if the input is HIGH
  20.     digitalWrite(ledPin, HIGH); // turn LED ON
  21.     playTone(300, 160); //play 160Hz tone for 300mS
  22.     delay(150);
  23.     if (pirState == LOW) { // we have just turned on
  24.       Serial.println("Motion detected!"); // We only want to print only if the output changes
  25.       pirState = HIGH; //value to store pir state
  26.     }
  27.   }
  28.   else {
  29.     digitalWrite(ledPin, LOW); // turn LED OFF
  30.     playTone(0, 0); //stop playing note
  31.     delay(300);
  32.     if (pirState == HIGH) { // we have just turned off Serial.println("Motion ended!"); // We only want to print if the output changes
  33.       pirState = LOW;
  34.     }
  35.   }
  36. }
  37. void playTone(long duration, int freq) { // duration in mSecs, frequency in hertz
  38.   duration *= 1000;
  39.   int period = (1.0 / freq) * 1000000;
  40.   long elapsed_time = 0;
  41.   while (elapsed_time < duration) {
  42.     digitalWrite(pinSpeaker, HIGH);
  43.     delayMicroseconds(period / 2);
  44.     digitalWrite(pinSpeaker, LOW);
  45.     delayMicroseconds(period / 2);
  46.     elapsed_time += (period);
  47.   }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement