I'm starting to learn about ultrasonic sensors. I've connected 3 together and am printing the distance they record onto the Serial Monitor, code is shown below.
The problem is I'm getting large values from time to time. For example, the readings from one sensor will be: 35, 36, ,35, 2995, 35, 36, etc. even though I placed a large piece of cardboard in front of them and shook it.
Is this because they're sensing the objects behind me, or is it a problem with the sensors?
PulseIn() returns 0 if it times out, that is, if the sensor doesn't see a reflection for whatever reason. It may be that the sensor times out sooner and that's what generates the 2995 value. This would make sense if the bogus values you see are relatively consistent. One way to address this is to pass a shorter timeout argument to PulseIn() which is using one second as the default. Thus something like "duration = pulseIn(echoPin, HIGH, 30000); " would timeout after 30,000 uS which is about 5 meters range (10 m round trip). If pulseIn() times out it will return 0 and you'll have to handle that.
On your code style, it would be more clear if you returned distance from the function SonarSensor rather than passing back through global variables.
With the above, something like this (compiled but not tested):
I prefer the solution of TomGeorge. Use the NewPing library. It works perfectly.
If you want to use the Tone() function in your code please also download the documentation from GitHub. By setting one value in the library you will regain the Tone() function.