Trying to clarify some concepts about the first if
:
When speaking in digital, one has in mind only the logical values 0 and 1, that is: booleans false and true . Therefore, one digital reading has a value "greater" than another only means that one is connected and another is off. Using a mathematical comparison operator in this case does not "close" for the purpose: after all, how do you compare if a true is greater than a false ? (Of course the compiler gives a way to resovler this, but for anyone who reads the code it can get kind of weird.
In the case of analog readings, the function to be used is analogRead(PINO)
. This function returns a value from 0 to 1023, since the Arduino analog digital converter works with 10 bits (so remember to use an int and not a char ) .
Now, how to convert the values 0 to 1023 into "digital"? You can do several analog readings and send through the serial to follow up on the Serial Monitor. This will tell you the cut-off distance of your sensor. For example, in the distance you want to measure, the reading returns around 700 (sometimes 695, 697, 702, etc.). Then one can consider a logical value 1 (the presence of an object) the readings below 710.
#define PINO 3
int valor = 0;
bool objetoPresente = false;
void setup()
{
Serial.begin(9600);
}
void loop()
{
valor = analogRead(PINO);
Serial.println(valor); // manda o valor para a serial
if (valor <= 710) {
// objeto na frente do sensor a uma distância limite
objetoPresente = true;
}
else {
objetoPresente = false;
}
}
Reference: link
PS: I've never worked with this sensor QTR Pololu, but googlando it, it has a specific library: link and some videos on Youtube.
I hope I have helped!