I'm trying to read data from two IR sensors but the results are wrong, some times returning 0 and mostly values don't make any sense.
The code i'm using is the following:
I tried with one, using necessary calculations to convert the results. The returned variables aren't stable but quite accurate. Then I connected the second sensor at A1 pin, GND, and 5V (as the other). Then it looks like something is really wrong :~ .
Thanks
Might add a delay between the readings,
Sometimes doing 2 analogRead()'s and only use the last one helps to settle the signal.
The returned variables aren't stable but quite accurate.
You can do 16 readings per sensor and average them
your code refactored with averaging and the use of arrays for some vars
int pin[2] = { A0, A1 }; // array with two pinnumbers
int distance[2]; // array to hold the distances
void setup()
{
Serial.begin(115200); // we go for max speed ;)
Serial.println("Setup...");
// ...
}
void loop()
{
// make 2 measurements
for (int p = 0; p < 2; p++) // do it twice for index 0 and index 1
{
distance[p] = 0;
for (int i=0; i< 16; i++) distance[p] += analogRead( pin[p] ); // make 16 readings
distance[p] /= 16; // average them
// optional delay(100) here..
}
// print them
Serial.println( "Sensor A0: " );
Serial.println( distance[0] );
Serial.println( "Sensor A1: " );
Serial.println( distance[1] );
// and wait
delay(1000);
}
When nothing is over the sensor, arduino returns many random variables from 0 to 300 or so (it happens with many codes ? found on internet which uses the IR sensor with robotics). However when results are converted in cm, apart from the fact these aren't steady, it returns the correct distance when detects an object.