i just got a ultrasonic sensor...it is a 4 pin (vcc/trig/echo/grnd) model...here is the 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);
}
here is what i get from the serial
4 cm
4 cm
4 cm
4 cm
5 cm
4 cm
4 cm
5 cm
4 cm
4 cm
when i remove the echo pin just to see what happens, just says out of range w/o any delays...i have it wired up just like u would think
US Sen Arduino
VCC --> 5v
Gnd --> Gnd
Trig --> 12
Echo --> 13
nothing more i can give u other than i am using the original arduino mega
Step 1, throw that code out.
Step 2, use the NewPing library (it includes sample code).
Step 3, make sure there's nothing in front of the sensor (wires or anything as the smallest thing can cause an echo).
Setp 4, enjoy!
If you run into problems, contact the author at the thread linked above. He's more than happy to help diagnose your problem.