Back to Parent

Final Code:

int ledPin = D1;                // Pin LED is connected to
int piezoBuzzerPin = D2;     // Pin Piezo Buzzer is connected to
int pirSensorPin = D0;               // PIN PIR Sensor is connected to

int motionDetected = 0;             // Start MotionDetected as low


int speakerPin = D2;

// create an array for the notes in the melody:
//C4,G3,G3,A3,G3,0,B3,C4
int melody[] = {1908,2551,2551,2273,2551,0,2024,1908};

// create an array for the duration of notes.
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {4,8,8,4,4,4,4,4 };

int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

int calibrateTime = 10000;      // wait for the thingy to calibrate

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(pirSensorPin, INPUT);     // declare the PIR sensor as input
  pinMode(piezoBuzzerPin, OUTPUT); //declare buzzer as output
  Serial.begin(9600); //Set serial out if we want debugging
  /*delay(5000); //Allow time for the PIR Sensor to calibrate*/
  Particle.variable("motion", &motionDetected, INT);
  pinMode( speakerPin , OUTPUT );
}
void loop(){
  motionDetected = digitalRead(pirSensorPin);  // Read the PIR sensor
  if(motionDetected == HIGH) //If motion detected
  {
    digitalWrite(ledPin, HIGH);
    digitalWrite(piezoBuzzerPin, 200);
    delay(100);
    digitalWrite(ledPin, LOW);
    digitalWrite(piezoBuzzerPin, 25);
    delay(100);
    playNotes();
  }
  digitalWrite(ledPin, LOW);
  digitalWrite(piezoBuzzerPin,LOW);
}


void playNotes()
{
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 8; thisNote++) {

      // to calculate the note duration, take one second
      // divided by the note type.
      //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
      int noteDuration = 1000/noteDurations[thisNote];
      tone(speakerPin, melody[thisNote],noteDuration);

      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      // stop the tone playing:
      noTone(speakerPin);
    }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0