Need Help Programing Sharp GP2D120

So i’ve been messing around with my arduino and i’ve been trying to do something simple that will better help me understand to to eventually build the robot i want to build.

Right I have the Sharp GP2D120 mounted to a servo, in the program i thought i had it set so that the sharp would take a reading and then either turn the servo it is mounted on in one direction or another based on the reading. However no matter what i do it just goes back and forth between center and the side it’s supposed to go to when the reading wasn’t close enough.

Here is the code i used. Any help would be greatly appreciated.

#include <Servo.h>

#define IR 0
Servo myservo;
int distance = 0;

void setup()
{
pinMode(IR, INPUT);
myservo.attach(9);
}

void loop()
{
myservo.write(90);
delay(1000);
analogRead(IR);
delay(2000);
if (IR <= 18)
{
myservo.write(180);
delay(1000);
return;
}
else {
myservo.write(0);
delay(1000);
return;
}
}

ps i realize that this is probably completely wrong, but it’s my first time. Be gentle

analogRead(IR);

The analogRead function returns a value that has some relationship to distance. You are throwing that value away.

if (IR <= 18)

IR is the pin number. It is hard-coded to 0, which will, at least for the foreseeable future, always by less than 18. So, the following block will always execute.

You need to capture the value returned by the sensor, and use that value in the if statement.

The values that are returned by the sensor will be in the range 0 to 1023. 18 is at the very low end of that range. the value that is returned is NOT a distance in inches, just so you know.

Hey there,

This example should help you :slight_smile: