Ping Sensor is Somewhat Working- Random distance reads

Hello,

This is not the same question I had earlier about the audio jack. I have finally set up my whole "air piano," and tested it with arduino coding. As a recap, the air piano uses a ping sensor and a 1/8'' audio jack female output. The ping sensor reads the distance between your hand and the sensor, and the arduino determines the sound to output in relation to that distance. My code seems to make sense, and my actual project does to. Here is the setup of my project, and my code.

Setup for Project:
Ping Sensor
-Signal connected to pin 7

1/8'' Audio Female Jack:
-Signal connected to pin 3
-Resistor: 220 ohms

Code:

int SensorPin=7;
int AudioPin=3;
int distance;
int note;
unsigned long pulseDuration=0;


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

void loop() {
  
  pinMode(SensorPin, OUTPUT); //Sends Ping
  digitalWrite(SensorPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(SensorPin, LOW);
  
  pinMode(SensorPin, INPUT); //Receives ping and calculates centimeter distance
  pulseDuration=pulseIn(SensorPin, HIGH);
  pulseDuration=pulseDuration/2;
  distance = int(pulseDuration/29);
  
  if (distance > 262){
    noTone(AudioPin);  //Makes sure that the sound stays within one C major octave
  }
  
  if (distance < 131){
    noTone(AudioPin);
  }
  
  else{
    distance = note;
    tone(AudioPin, note);
  }
  delay(20); //Take a break
}

My problem is that the speaker ends up outputting random pitches. What am I doing wrong?

Thanks,

I_Got_Pi

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

I_Got_Pi:
My problem is that the speaker ends up outputting random pitches. What am I doing wrong?

Do the output glitches correspond to glitches in your position sensing inputs?

I'd add some serial debugging prints to find out what your actual values look like.