PID controller, levitating pin pong ball. Help with ultrasonic sensor

I’m working on a PID control experiment. Got the idea from https://www.vernier.com/engineering/arduino/projects/levitating-ping-pong-ball/

Basically there is a ping pong ball in a cylinder and a fan at the bottom and an ultrasonic sensor on top to measure the distance. Im using the HC-SR04 sensor.

What I noticed was that sensor wasn’t measuring the distance fast enough and the second thing I noticed was that sometime it shows negative values.

Here is the bit of code used for the ultrasonic sensor, I haven’t included the whole code but if anyone wants to know, I could paste the whole code too.

I have modified the code posted by Brett Beauregard - PID Simple Example (Augmented with Processing.org Communication) Version 0.3

#include <PID_v1.h>

//Define Variables we'll be connecting to
double Setpoint, Distance, Output;
int Duration;
int  outputPin = 3;

//Specify the links and initial tuning parameters
PID myPID(&Distance, &Output, &Setpoint, 2, 5, 1, DIRECT);
const int trigPin = 8; //trigger pin
const int echoPin = 7;// echo pin


unsigned long serialTime; //this will help us know when to talk with processing

void setup()
{
  //initialize the serial link with processing
  Serial.begin(9600);


  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Setpoint = 100;

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  //pid-related code
  
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  Duration = pulseIn(echoPin, HIGH);
  Distance = (Duration / 2) / 29.1;
  
  
  myPID.Compute();
  analogWrite(outputPin, Output);

Yami89:
What I noticed was that sensor wasn't measuring the distance fast enough and the second thing I noticed was that sometime it shows negative values.

As pulseIn returns an unsigned long, storing the result in an int could be part of the problem.

int Duration;

The measurement is too slow? Could specifying a timeout in pulseIn help?

BTW If you get bad values you should not pass them to PID, should you?

@Whandall, yes thats true I don't want to be sending wrong values for the controller. Good point about the pulseIn and int Duration; going to try that now.

And also how can I write a code so that Arduino ignores out of range values. Would it make sense to constrain the Distance variable to certain upper and lower value.