error values while measuring pulse distance.

hello all,
This is my first post so please excuse me if this is not in the right place or in the right format.

I am using a Arduino UNO, 24v solid state relay and a optical sensor, to measure the objects that crosses sensor.
As attached Png image file.

And my code is

int pin = 7;
unsigned long duration;

void setup()
{
Serial.begin(9600); // open the serial port at 9600 bps:
pinMode(pin, INPUT);
}

void loop() {

Serial.print("\n"); // prints a tab
duration = pulseIn(pin,HIGH);
Serial.print(duration,DEC);
delay(250);

}

But the decimal value which i see in serial monitor is not constant and i see more error values.

I don't know if this is because of the program or the limits of the hardware?

Any help you can give will be most useful, thank you for your time.

PULSEIN.png

What's connected to pin 7?
What's the relay going to do?

This is my first post

No, it's your third.

You can edit your post and add these - don't worry, they're spares I had lying around [code][/code]

But the decimal value which i see in serial monitor is not constant and i see more error values.

You're going to have to define some terms.

first I thank u for the reply.

sorry I am using pin 4 instead of pin 7.

And my objective is to calculate the width of the Paper in my industry , a defective product(paper) will have more width when compared to the good product(paper).

the laser sensor is fixed above the paper conveyor. And the sensor gives long output for long product(defective) and a short output for good product(paper) and i am here trying to find the defective one.

And my code is

int pin = 4;
unsigned long duration;

void setup()
{
Serial.begin(9600); // open the serial port at 9600 bps:
pinMode(pin, INPUT);
}

void loop() {

Serial.print("\n"); // prints a tab
duration = pulseIn(pin,HIGH);
Serial.print(duration,DEC);
delay(250);

}

But the decimal value which i see in serial monitor is not constant and i see more error values.

I don't know if this is because of the program or the limits of the hardware?

Any help you can give will be most useful, thank you for your time.

Well, start by posting a complete schematic of your setup, make all grounds are connected together.
Post a link to the optical sensor.
Perhaps use
pinMode(pin, INPUT_PULLUP);
if your sensor pulls the pin low during one of its levels (paper or no-paper).

 Serial.print("\n");   // prints a tab

If you are going to have useless comments, you MUST make the code agree with the useless comments.

Why are you using pulseIn()?

You should be using the state change detection example, recording when the state changes.

Periodically, you check to see if the pin has been in the bad state for too long. For periodically, that means on every pass through loop().

The Serial.print() is useless, and the delay() absolutely has to go.