Conversion value analog to digital Arduino

0
Hello, I'm developing a line follower robot the sensor reading is analog (0 - 255) Polulu QTR, but the project requires that digital values (0 - 1) be used in comparisons of values like:

if(digitalRead(sensor1) > digitalRead(sensor2)){ ... } 

So how can I convert from analogue to digital? It would be possible to accomplish this with PWM as:

#define pin = 13; //pino PWM
void setup() { ... }
int leitura = digitalRead(pin); //0 - 1

Thank you very much in advance!

    
asked by anonymous 15.09.2016 / 02:22

1 answer

0

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!

    
15.09.2016 / 15:58