Pages: [1]   Go Down
Author Topic: Sharp IR Remapping  (Read 250 times)
0 Members and 1 Guest are viewing this topic.
Wrexham, North Wales
Offline Offline
Full Member
***
Karma: 0
Posts: 135
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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.
Logged

M

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 178
Posts: 8060
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
  int irVal = analogRead(irSensor);
  int irMapVal = map(constrain(irVal,102,563), 102, 563, 0, 100);
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Wrexham, North Wales
Offline Offline
Full Member
***
Karma: 0
Posts: 135
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
  int irVal = analogRead(irSensor);
  int irMapVal = map(constrain(irVal,102,563), 102, 563, 0, 100);

Thanks very much, thats perfect  smiley

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?
Logged

M

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 178
Posts: 8060
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Wrexham, North Wales
Offline Offline
Full Member
***
Karma: 0
Posts: 135
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

That makes perfect sense  smiley

Thanks for your help, much appreciated!
Logged

M

Pages: [1]   Go Up
Jump to: