Don’t take this the wrong way, but even that short one is a pain to read without some formatting and indentation. Oh, and comments…
Also, please put any code inside the # tags.
Anyway, 5 pins? 2 for power, 2 for I/O, and one for…? (IE some small explanation of your ultrasonic transducer device is appreciated). You also need to know the kind of logic on its output (is it high when reciving the echo, or low? Or even digital at all? But I suspect it is), and code accordingly.
As the I/O pins don’t change direction, there is no point in setting up pinmode through each loop. Do that once in the setup().
I’m not sure why your serial stops receiving or sending data.
If your transducer thingy works like I think, I think you could use the code posted in post #11 in this thread. (coincidentally my post:p) with little modification (just change the pins used). As I stated there it was kinda based on the Ping ))) example, except I didn’t use that exact method with pulseIn… Btw that Ping example code seems to have gone missing…
Anyway, Im just gonna go ahead and repeat that code here. Not saying this is the only or best way, just an example.
/* Ultrasonic transmitter/receiver test
2010.04.28 raron - but based on the Ping))) example at http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor
const int pingOutPin = 7; // Connected to the simple H-bridge and the ultrasonic transmitter
const int pingInPin = 8; // Connected to the ultrasonice receiver via op-amp circuit
const long timeout = 40000; // us, gives up listening after a distance of 6.89 meters one way
digitalWrite(pingInPin, LOW); // no internal pullup
long pingStartTime, echoTime, inches, cm;
pingStartTime = micros();
echo = digitalRead(pingInPin);
echoTime = micros() - pingStartTime;
} while (echo == false && echoTime<timeout);
// convert the time into a distance
inches = microsecondsToInches(echoTime);
cm = microsecondsToCentimeters(echoTime);
long microsecondsToInches(long microseconds)
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
long microsecondsToCentimeters(long microseconds)
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;