Go Down

Topic: Sharp IR Remapping (Read 405 times) previous topic - next topic

daz1761

I've just purchased a Sharp IR Range Finder 20cm to 150cm.  I'm trying to remap the ADC so that when nothing is in range it reads 0 and when something has approached the 20cm limit to read 100. 

This is my code:

Code: [Select]
#define irSensor 1

void setup () {
  Serial.begin(9600);
}

void loop() {
 
  int irVal = analogRead(irSensor);
  int irMapVal = map(irVal, 0, 1024, 0, 100);
  Serial.println(irMapVal);
  delay(1000);
}


For some reason my maximum reading within the boundaries is 50 not 100 as I expected.
M

johnwasser

If you look at the specifications you will see that the output range for the GP2Y0A02 is about 0.5V to 2.75V.  With a 5V analog input that's about 102 to 563.  You might want to constrain the inputs before mapping:
Code: [Select]

  int irVal = analogRead(irSensor);
  int irMapVal = map(constrain(irVal,102,563), 102, 563, 0, 100);
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

daz1761


If you look at the specifications you will see that the output range for the GP2Y0A02 is about 0.5V to 2.75V.  With a 5V analog input that's about 102 to 563.  You might want to constrain the inputs before mapping:
Code: [Select]

  int irVal = analogRead(irSensor);
  int irMapVal = map(constrain(irVal,102,563), 102, 563, 0, 100);



Thanks very much, thats perfect  :)

If you don't mind me asking, how did you work out the 102 to 563 range with the incoming and outgoing voltages?  I know the Arduino Uno ADC is 10bit (0, 1024).  Did you multiply the 0.5 and 2.75 by something?
M

johnwasser

The default analog input reference voltage is 5V.  That means that 0V maps to 0 and 5V maps to 1024 (yes, even though the highest number you can get is 1023).

To calculate the analog input number from a voltage, divide the voltage by 5 and multiply by 1024.

0.5V / 5V = 0.1 * 1024 = 102.4
2.75V / 5V = 0.55 * 1024 = 563.2

Of course the actual numbers are truncated to integers: 102 and 563.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

daz1761

That makes perfect sense  :)

Thanks for your help, much appreciated!
M

Go Up