Let's Make Robots!

Hc-SR04 ultrasonic sensor advice needed

Hi Im new to programming ini general, Ive been through the sample codes in "getting started with Arduino" and now Im trying out some sensors I have here. The first on eis the HC-SR04 ultrasonic I have it working using this code,

/*
 HC-SR04 Ping distance sensor]
 VCC to arduino 5v GND to arduino GND
 Echo to Arduino pin 13 Trig to Arduino pin 12
 More info at: http://goo.gl/kJ8Gl
 */

#define trigPin 12
#define echoPin 13

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

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

My question is how would I go about getting a servo to rotate with this sensor mounted on top of it and compare distances on both sides and make a decision ie. Go forward or Stop or whatever?.Ive been searching for a few days now and could only find something similar using a PING sensor not the HC-SR04 but I have not been able to modify it due to lack of knowledge.

Any sketches or pointers would be great.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thank you kariloy I will have a look at it now.

 

Thanks a bunch for your time and patience.

Well basically you'd create an array to store readings say center, read distance and store it, move servo left, read and store value, and the same for the right side. Then you could compare those stored values.

If you want take a peek at: http://letsmakerobots.com/node/32703

I have the code at the bottom of my robot post. I should be fairly easily to understand I even have some guiding comments on the code.