Ultrasonic Sensor

Library:New Ping

#include <NewPing.h>

 

#define TRIGGER_PIN  5  // Arduino pin tied to trigger pin on the ultrasonic sensor.

#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.

#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). 

 

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance


 

void setup() {


  Serial.begin(9600);

 

}

 

void loop()  {

 

 Serial.println(sonar.ping_cm());

 Serial.print("cm");

 delay(100);


}

//This makes a tone proportional to distance


#include <NewPing.h>


#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.

#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.

#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.


void setup() {

Serial.begin(9600);

}


void loop() {


Serial.print("Ping: ");

Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)

Serial.println("cm");


int thisPitch = map(sonar.ping_cm(), 0, 200, 100, 5000);

tone(9, thisPitch, 10);

noTone(9);

delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.


}

//Alternate Code, not using the NewPing library:

// Define pins for the HC-SR04

const int trigPin = 7;  // Trigger pin connected to pin 7

const int echoPin = 8;  // Echo pin connected to pin 8


void setup() {

  // Initialize the serial monitor

  Serial.begin(9600);


  // Configure trigger pin as an output

  pinMode(trigPin, OUTPUT);

  // Configure echo pin as an input

  pinMode(echoPin, INPUT);

}


void loop() {

  // Clear the trigger pin

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);


  // Send a 10-microsecond pulse to trigger the sensor

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);


  // Read the duration of the echo signal

  long duration = pulseIn(echoPin, HIGH);


  // Calculate the distance in centimeters

  float distance = duration * 0.034 / 2;


  // Print the distance on the serial monitor

  Serial.print("Distance: ");

  Serial.print(distance);

  Serial.println(" cm");


  // Add a short delay before taking the next measurement

  delay(500);

}