/* 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 Original code improvements to the Ping sketch sourced from Trollmaker.com Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar Modified by Tolson Winters (Aug 27, 2014) for simplified serial monitor reading. Code is further modifyied by DavidDrones to fit this projects needs. */ const int trigPin = A0; const int echoPin = A3; const int buzzer = 4; void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(buzzer, OUTPUT); //pin 7 powers the sonar sensor pinMode(7, OUTPUT); digitalWrite(7, HIGH); } 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 >= 2000 ) { Serial.println("Out of range"); } //if nothing in sight low beep else if (distance < 390) { tone(buzzer, 500, 5000); } //high beep if something is close else if (distance < 15) { tone(buzzer, 2000); } else { //normal beep tone(buzzer, 1000, distance*4); } delay(500); }