Sharp IR distance sensor as a "button"

Hey, I'm currently working on a project to make a Sharp IR 2Y0A02 sensor to work as a keyboard button in a game. http://www.acroname.com/robotics/parts/R144-GP2Y0A02YK.html

To do this I first wanted to test it with a led and see if I could turn on the led by activating my IR sensor.

I've been looking at these homepages:
http://www.e-gadget.com.au/category/63-arduino-duemilanove-and-infrared-sensor-tutorial.aspx
http://luckylarry.co.uk/arduino-projects/arduino-using-a-sharp-ir-sensor-for-distance-calculation/

So far I've thought of doing it like this. I haven't tested it yet, because I'm not sure that it is correct.

int IRpin = 1;                       // analog pin for reading the IR sensor
					
int ledPin = 10;		 	// Setup LedPin on Digital Pin 10


void setup() {

 pinMode(ledPin, OUTPUT);		// Initialize the LED pin as an output:

Serial.begin(9600);                    // start the serial port


void loop()  
{  
 
  if (sensors[0] < 750)
  {  
    // Turn on the LED if we get a High Reflectance.    
    digitalWrite(ledPin, HIGH); 
   
  } 
  // Turn off the LED if we have a Low Reflectance.
  else digitalWrite(ledPin, LOW);  
}

What do you think of this?
At the moment, I'm not sure what I should name the sensors[0] or what distance it should be set at.
Also, do I need to program it to show me the distance time?

Hope you will be able to help me :slight_smile:

Welcome in the wonderful world called Arduino ,

First use the # button if you want to publish code (you can modify your 1st post, select the code and press the #button)

The reading of the sensor will fail, so I rewrote your code a bit so it should work

#define THRESHOLD 750

int ledPin = 10; // Setup LedPin on Digital Pin 10

void setup() 
{
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600); 
}

void loop() 
{ 
  int sensorValue = analogRead(A0);

  Serial.println(sensorValue);

  if (sensorValue < THRESHOLD )
  {
    digitalWrite(ledPin, HIGH); //High Reflectance.  
  }
  else 
  {
    digitalWrite(ledPin, LOW); // Low Reflectance.
  }
}

To improve the stability of the readings, you can repeat them in a loop like in the function below.

unsigned int sharpRawAvg()
{
  unsigned long raw = 0;
  for (byte i=0; i<32; i++) 
  {
    raw += analogRead(A0);
    //delay(1);
  }
  return raw/32;
}

You can add this function to your code and call it from your sketch
replace
int sensorValue = analogRead(A0);
with
int sensorValue = sharpRawAvg()

succes,
Rob

Thanks a lot, I'm going to try it today :slight_smile:

I dont know yet what my threshold is, but I'm going to test it today. And I guess I should just use the number I get from that test.

So if this works, should I just replace the int ledPin = 10 and the other ledPin with the keyboard output I'm going to use? I opened a keyboard and took the keyboardchip out.