how to invert input from sensor?

edited July 2017 in Arduino

hello, beautiful people.

I'm working with an ultrasonic proximity sensor from which I get values that range from 0 to 200, and are directly proportional to the distance the object measured by the sensor is from it, in centimeters. if an object touches the sensor, the value measured is 0.

I would like to invert this connection: instead of a directly proportional input, an inversely proportional one, from which I get bigger values the closer the object is to the sensor. how could I achieve this?

Answers

  • Answer ✓

    Question: 200 is in actual distance units? If 200 is the max value then you could do

    final int MINVAL=0;
    final int MAXVAL=200;
    
    final int NEW_MINVAL=0;
    final int NEW_MAXVAL=200;
    
    float invPropValue=map(inSensor,MINVAL,MAXVAL,NEW_MINVAL,NEW_MAXVAL); 
    

    So if the object is close to the sensor, let's say at zero, invPropValue will be 200.

    Kf

  • I think you meant

    final int MINVAL=0;
    final int MAXVAL=200;
    
    final int NEW_MINVAL=200; // these two
    final int NEW_MAXVAL=0; // being switched

    Anyway, that worked for me!! Thank you :bz

  • My mistake. You are right!

    Kf

  • edited July 2017

    Or, to hardcode it:

    float invPropValue=200-inSensor;
    

    map() is flexible in the general case, but a bit overkill for a zero-max inversion -- at least, overkill if performance is an issue. Just subtract and you are done.

Sign In or Register to comment.