#include <HCSR04.h>
#include <Servo.h>
#include "pitches.h"
UltraSonicDistanceSensor distanceSensor(12, 13);  // Initialize sensor that uses digital pins 13 trigger and 12 eco.
Servo myservo;
int melody[] = { 
                 NOTE_C6, NOTE_F5, NOTE_F5, NOTE_C6, NOTE_F5, NOTE_F5, NOTE_C6, NOTE_F5, NOTE_CS5, NOTE_F5,
                 NOTE_B5, NOTE_E5, NOTE_E5, NOTE_B5, NOTE_E5, NOTE_E5, NOTE_B5, NOTE_E5, NOTE_C6, NOTE_E5,
                 NOTE_B5, NOTE_E5, NOTE_E5, NOTE_B5, NOTE_E5, NOTE_E5, NOTE_B5, NOTE_E5, NOTE_C6, NOTE_E5 }; // All the melody must be inserted note by note.
int duration = 200;  // 200 miliseconds per in between notes.

unsigned long mus;
unsigned long ser;

void setup() {
  Serial.begin(9600);  // We initialize serial connection so that we could print values from sensor.
  myservo.attach(8);   // We determine that the servo is connected to digital pin 8.
  pinMode(10, OUTPUT); // We determine that the leds are connected to digital pins 10 and 11.
  pinMode(11, OUTPUT);
}

void loop() {

  int dist = distanceSensor.measureDistanceCm();  // We determine that the value of ¨dist¨ is the distance that the ultrasonic sensor measures.
  if (dist > 13) {  // If the ultrasonic sensor detects a distance that is more than 13cm (the diameter of the Halloween basket is 17cm) initiate.
    myservo.write(90); // The angle of rotation of the servo is 90.
    digitalWrite(10, LOW);  // Keep the leds off.
    digitalWrite(11, LOW);

  } 
  else {  // If the ultrasonic sensor detects a distance that is less than 13cm (someone has put their hand in the basket) initiate.
    digitalWrite(10, HIGH); // Turn leds on.
    digitalWrite(11, HIGH);
    mus=millis();  // The variable ¨mus¨ and ¨ser¨ depend on millis (which returns the number of milliseconds since they have been called) start counting.
    ser=millis();
    int nota=0; // The note starts at value 0.
    while(nota<30)  // nota runs up to note 30 and until the song ends the following happens:
    {
      if(millis()-mus>=250) // 0.25 seconds after inserting your hand into the bucket, the song begins to play.
      {
        tone(9, melody[nota], duration); // The song start ringing note by note.
        nota++; // One after the other.
        mus=millis(); // The variable ''mus'' restarts.
      }

      if(millis()-ser>=500) // 0.5 seconds after inserting your hand into the bucket, the skull starts rotating.
      {
        if(myservo.read()==60)  // The servo will go to 60 degrees.
          myservo.write(120);  // And then to 120 degrees.
        else
          myservo.write(60); // When the song ens, the servo returns to its original position
        ser=millis(); // The variable ''ser'' restarts.
      }
    }
  }
}
