Analog to Arduino digital value conversion

Asked

Viewed 137 times

0

Hello, I am developing a line follower robot the sensor that performs the reading is analog (0 - 255) QTR Polulu, but the design requires that digital values (0 - 1) be used in the comparisons of values such as:

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

So how can I convert an analog value to digital? It would be possible to do this with PWM as:

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

Thank you very much from now on!

  • Pololu sensor correction!

  • Related answers: http://answall.com/a/9111/3084 and http://answall.com/a/142023/3084

1 answer

0

Trying to clarify some concepts about the first if: When talking about digital, one has in mind only the values 0 and 1 logical, ie: booleans false and true. Therefore, a digital reading has a value "higher" than another only means that one is on and the other is off. Using a mathematical comparison operator in this case does not "close" for the purpose: after all, how to compare if a true is greater than a false ? (Of course, the compiler finds a way to solve this, but for those who read the code it can get a little strange.

In the case of analogue readings, the function to be used is analogRead(PINO). This function returns a value from 0 to 1023, since the Arduino digital analog converter works with 10 bits (so remember to use a int and not a char). Now, how to convert the values 0 to 1023 into "digital"? You can do various analog readings and send by serial to follow on Serial Monitor. With this you will know what is the cutting distance/limit 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: https://www.arduino.cc/en/Reference/AnalogRead

PS: I’ve never worked with this QTR Pololu sensor, but googlando it, it has a specific bibliotea: https://www.pololu.com/docs/0J19/all and some videos on Youtube.

I hope I’ve helped!

  • Thank you so much, so there’s no need to compare if that way I can do so if(objetoPresente){ } //se for true

  • In fact, you don’t even need the variable objetoPresente, but you need the if (valor <= 710). You can run what you need directly from if by replacing the objetoPresente = true by treatment if the object is in front of the sensor and in the case of else if the object is not in front.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.