Ping sensor and speaker

Ive have stitched together this code just for fun to try to make some sound experiments with ping sensors. This however get boring quite fast. :slight_smile: You might have some suggestions to further experiments? Thanks alot!

const int pingPin = 7;
int soundpin = 9;

void setup() {

  Serial.begin(9600);
  pinMode(soundpin, OUTPUT);
}

void loop()
{
  long duration, inches, cm;

  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  cm = microsecondsToCentimeters(duration);
  
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);

   int level = cm;
    level = map(level, 0, 40, 100, 400);
  
    if(cm < 40){
        
       tone(9, level);
    }
    else {
      noTone(9);
    }

}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

Instead of playing like a slide-whistle you could have a list of note frequencies and use the distance to pick from the list. You could use a pentatonic scale (C D E G & A) and they will all sound good together.

Equal-Tempered tuning [A4 = 440Hz]

| | Octave=1 | Octave=2 | Octave=3 | Octave=4 | Octave=5 | Octave=6 | | - | - | - | - | - | - | - | | A | 55.000 | 110.000 | 220.000 | 440.000 | 880.000 | 1,760.000 | | C | 65.406 | 130.813 | 261.626 | 523.251 | 1,046.502 | 2,093.005 | | E | 82.407 | 164.814 | 329.628 | 659.255 | 1,318.510 | 2,637.020 | | G | 97.999 | 195.998 | 391.995 | 783.991 | 1,567.982 | 3,135.963 |