Robin2:
You don't have any Serial.print statements in your program to enable you to check the values that are actually being used.
...R
True, not in this one. This is because I don't want to connect the Arduino to my laptop while it's also being connected to the 12V battery. I've made a little setup with just the Arduino and the sensor. When I hold a book just before the sensor, it starts outputting values in the range of 2001cm... it does read 1, 2 cm etc but it has spikes from 200 to 2001cm. So that's weird. A friend of mine who is using the same sensor for a project is having the same quirk.
Connecting the Arduino to the laptop won't cause a problem.
I can't make sense of your other comments without seeing the code that gave rise to them. In any case it would be much better to get debug data from the actual program.
You need to know the data values when the behaviour changes.
When I hold a book just before the sensor, it starts outputting values in the range of 2001cm... it does read 1, 2 cm etc but it has spikes from 200 to 2001cm. So that's weird. A friend of mine who is using the same sensor for a project is having the same quirk.
So, despite not getting reliable data from a possibly defective or miswired sensor, you are just going to assume that the data is perfect, and write a sh*tload of code to use that data, and then not understand why the code doesn't work.
PaulS:
So, despite not getting reliable data from a possibly defective or miswired sensor, you are just going to assume that the data is perfect, and write a sh*tload of code to use that data, and then not understand why the code doesn't work.
Some people just amaze me.
Others just amuse me.
You're funny.
Dude, I said it was a test of the reliability of the sensor. It DID proof that, for one reason or another, the sensor is inaccurate at close distances. I'm using millis() now, and that fixed this problem. The closest measuring distance of the unit is ~2 cm, which corresponds with the output in the serial monitor.
I'm not asking for these kinds of comments, it's not a high school playground.