Ultrasonic Distance Sensor Experiments

After completing the Ultrasonic Distance Sensor project, test yourself by trying these experiments.

1 What is the distance between the table top and the ceiling?
2 What is the furthest distance to an object that the ultrasonic sensor can sense?
3 Modify the code to turn on the internal LED on pin 13 when there's an object less than 15 cm away, and turn off the LED when there's no object within that range.
// this function calculates and returns the distance
// as obtained from the ultrasonic sensor
int distance() {
  int trigPin = 11;
  int echoPin = 12;  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // STEP 1
  // The next five lines will send out one ultrasound pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // STEP 2
  // The pulseIn command starts the timing and wait for the echo
  // when it hears the echo it will return the time in microseconds
  int duration = pulseIn(echoPin, HIGH);

  // STEP 3
  // Calculate the distance (in cm) based on the time from STEP 2 and the speed of sound
  // the calculated distance is returned by the function
  return duration/58.2;
}

void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  int d = distance();  // call the distance() function to get the distance
  if (d < 15) {
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}
4 Modify the code to turn on the internal LED on pin 13, and also sound the buzzer on pin 2 when there's an object less than 15 cm away. Turn both the LED and the buzzer off when there's no object within that range.
void loop() {
  int d = distance();  // call the distance() function to get the distance
  if (d < 15) {
    digitalWrite(13, HIGH);
    tone(2, 440);
  } else {
    digitalWrite(13, LOW);
    noTone(2);
  }
5 Make the internal LED on pin 13 blink in such a way that the closer an object is the faster the LED will blink. The LED will blink very slow when no object is in front of the sensor.
void loop() {
  int d = distance();  // call the distance() function to get the distance
  digitalWrite(13, HIGH);
  delay(d*12);
  digitalWrite(13, LOW);
  delay(d*12);
}
6 Modify the code to play the StarWars theme song when there's an object less than 15 cm away.
7 Connect both an ultrasonic distance sensor and a 7-segment LED display. Write the code to show on the 7-segment LED display the number of centemeters (only from 0 to 9) between the distance sensor and an object.