Ultrasonic sensor

So i just started learning how to use this. I'm trying to use an ultrasonic sensor to detect collisions before a robot hits. Here's the code

#include <Servo.h>

Servo myservo;
Servo myservo2;
#define echoPin 2
#define trigPin 3

void setup()
{
myservo.attach(10);
myservo.write(270);
myservo2.attach(9);
myservo2.write(-270);

pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
}

void loop()
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance (duration/2) / 29.1;

if (distance > 100)
{
myservo.write(270);
myservo2.write(270);
Serial.println("All Good");
}

if (distance <= 100)
{
myservo.write(0);
myservo2.write(0);
Serial.println("COLLISION DETECTED")
}
}

Let me know what you guys think

I think you'll have a problem writing a negative angle to a servo.

I think the compiler won't like your code.

I think you should use code tags when posting code.

I think the topic title is terrible.

I think Dominic Raab is unsuitable to deputise for Boris Johnson.

I think I'd like another bottle of the Italian wine I drank with a dinner.

I think I'm wondering why you're looking at a ten year-old topic.

Might want to look at the Servo library reference.

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :slight_smile:

Servo.write() takes values from 0-180. So 270 and particularly -270 are meaningless.

Then you have an = and a ; missing. The compiler will have told you exactly where.

Steve

Hi,
What about your code?
Does it compile?

Can you please explain your project hardware?
Are you using a continuous servo as the drive motor?

Tom... :slight_smile: