1

I am using this example on how to use a photoresistor to detect the value of light that the sensor is getting but I want to convert the reading of the resistor to a percentage but I can't use the map() function from the Arduino docs but I can implement something similar to it

so I created this simple function

float photo_resistor(int pinNum)
{
    float reading = analogRead(pinNum);
    if (reading == 54)
    {
     return 0.0;
    }
    return (reading - 54)/(100/920);

}

as in the docs I want to use an output range from 0 to 100 and the minimum reading i got is 54 and the maximum is 974

return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
// this becomes (x - 54)*(100 - 0 ) / ( 974 - 54) + 0;
// (x-54)/(100/920);

but this does not output a value from on the scale from 0-100

enter image description here

2
  • 1
    your question is about arithmetic, not about Arduino
    – jsotola
    Jun 9 at 17:26
  • 2
    think of a basket that can hold 20 apples maximum ... there are 6 apples in the basket ... how full is the basket, expressed in percent?
    – jsotola
    Jun 9 at 17:27

1 Answer 1

4

You wrote:

return (reading - 54)/(100/920);

In C++, 100/920 is zero. This is because, when both operands are integers, the division operator performs an integer division. You can overcome this problem by making sure that at least one of the operands is a floating point number. For instance, 100.0/920 is roughly 0.1087.

However, your division is backwards. You probably mean

return (reading - 54) * (100.0/920);
1
  • I'd use return max(0.0, min(100.0, (reading-54.0)*(100.0/920))); -- this makes sure that no values outside the range 0.0 .. 100.0 are ever returned, even when another photoresistor with slightly different tolerances is being used.
    – orithena
    Jun 10 at 14:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.