proximity controlled servo!! help please soo close!

hello,

i am trying to create a vilros sg90 servo controlled by a hc-sr04 ultrasonic sensor on my arduino uno.
i dont understand what I am doing wrong? I want at a certain distance, the servo begins to rotate, and follow your proximity via the angle of the servo. can someone overlook the code?


#define trigPin 3
#define echoPin 2
#include <Servo.h>

Servo myservo;

void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.attach(9);
}

void loop()
{
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2); //defines ping sensor

int val = digitalRead(distance); //tells ardiuno to read distance as val
val = map(val, 300, 500, 0, 179); //define the value of distance to angle of servo arm
myservo.write(val); //servo functions based off of val
delay(15);

Serial.print(distance);
Serial.print(" ");
delay(500);
}

Something went very wrong here:

int val = digitalRead(distance);    //tells ardiuno to read distance as val
val = map(val, 300, 500, 0, 179);   //define the value of distance to angle of servo arm

digitalRead returns zero or one. What values are you getting for distance? If it's 300 to 500, you're asking the Arduino what it has on pins in that range - not likely to work well.

Drop the digitalRead. I'd imagine the map was supposed to be:

val = map(distance, 300, 500, 0, 179);   //define the value of distance to angle of servo arm

That seems to work, but be sure to declare "int val;" before the line
val = map(distance, 300, 500, 0, 179);

BTW - I had better luck with a shorter range of distance - 30 cm to 300 cm rather than 300 - 500

Here's what I came up with - I hope it helps

#include<Servo.h>
Servo myservo;
#define trigPin 3
#define echoPin 2

void setup()
{
myservo.attach(9);
Serial.begin (9600);
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
}

void loop()
{
int val; // declared the int "val"
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
val = map(distance, 30, 150, 0, 179); // as per wildbill's suggestion
myservo.write(val);

delay(150);

Serial.print(distance);
Serial.print("cm");
Serial.println();
delay(500);
}

I would add this line to limit distance:

 int val = digitalRead(distance);    
val = constrain (val, 300,500);
 val = map(val, 300, 500, 0, 179)