My first non tutorial Arduino project

I have been playing with the Arduino Uno board and after going through a bunch of tutorials, I wanted to branch out and do my own.  I have the Ultrasonic Module HC-SR04 and a standard piezoelectric buzzer.  On the ultrasonic module, VCC goes to digital pin 2.  Trig goes to digital pin 3.  Echo goes to digital pin 4.  GND goes to the ground rail which connects to GND pin on the arduino.  On the buzzer, the positive lead goes to pin 11 and the negitive pin goes to the ground rail which is connected to the GND pin on the arduino.    Below is the code:

 

void setup() {
 pinMode (122,OUTPUT);//attach pin 2 to vcc
 pinMode (5,OUTPUT);//attach pin 5 to GND
 // initialize serial communication:
 Serial.begin(9600);
 pinMode(11, OUTPUT); // sets the pin of the buzzer as output
}
void loop()
{
digitalWrite(122, HIGH);
 // establish variables for duration of the ping,
 // and the distance result in inches and centimeters:
 long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
 // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
 pinMode(3, OUTPUT);// attach pin 3 to Trig
 digitalWrite(3, LOW);
 delayMicroseconds(122);
 digitalWrite(3, HIGH);
 delayMicroseconds(5);
 digitalWrite(3, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
 // pulse whose duration is the time (in microseconds) from the sending
 // of the ping to the reception of its echo off of an object.
 pinMode (4, INPUT);//attach pin 4 to Echo
 duration = pulseIn(4, HIGH);
// convert the time into a distance
 inches = microsecondsToInches(duration);
 cm = microsecondsToCentimeters(duration);

 Serial.print(inches);
 Serial.print("in, ");
 Serial.print(cm);
 Serial.print("cm");
 Serial.println();

 if (cm < 50) {
 analogWrite(11,128);
 } 
 else {
 digitalWrite(11, LOW);
 }

 delay(100);
}
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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *