// Declare variables
unsigned long duration;// variable that stores a positive value
int DT=500;
int distance;
int sensordist;
const int trigPin = 10;
const int echoPin = 9;
void setup() {
pinMode(trigPin,OUTPUT); //remember all pins are input unless specified otherwise
pinMode(echoPin,INPUT);
pinMode (8,OUTPUT); // buzzer
analogRead (A2); // research pull up resistor
Serial.begin(9600); // Starts the serial communication
}
void loop () {
digitalWrite(trigPin,LOW); // clear the pin
delayMicroseconds(2); // send out pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(12);
digitalWrite(trigPin, LOW);// listen for reflected sig.
duration = pulseIn(echoPin, HIGH);// calculate distance
distance = duration*0.0344/2; //this is in mm, travels to and from target ( hence ÷ 2)
//display to screen
Serial.print("distance = ");
Serial.print(distance);
Serial.println(" mm");
delay (100);//delay}
// determines when to play song
sensordist=analogRead(A2)/4;
if (distance<sensordist){
song();
}
else{
delay(DT);
}
}
void song(){
int beat=50;
float semibreve=4*60000/beat;
float minim=2*60000/beat;
float crotchet=60000/beat;
float dottedcrotchet=1.5*crotchet;
float dottedminim=1.5*minim;
float quaver=crotchet/2;
float semiquaver=crotchet/4;
float dottedquaver=quaver*1.5;
float triplet=crotchet/3;
// insert code here///
tone (8,294,crotchet); delay(crotchet);//low D
tone (8,587,crotchet); delay(crotchet);// D
}