HC-SR04 Ultrasonic Distance Sensor Test Code
Following code requires downloading and installing the NewPing library into the Arduino IDE
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home#!download-install
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home#!download-install
// TestCode for ultrasonic Sensor HC-SR04 https://www.amazon.com/gp/product/B01COSN7O6/
// D. Brancazio 7/10/2017
// Does a ping about 20 times per second and displays distance read
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 3 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 2 // 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.
unsigned int thereBackTime = 0; //time for ping to go there and back, in microseconds
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
int distance;
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the least delay between pings
distance = sonar.ping_cm(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print (distance); // print result
Serial.println("cm");
//could use some error checking (0 = outside set distance range)
}
// D. Brancazio 7/10/2017
// Does a ping about 20 times per second and displays distance read
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 3 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 2 // 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.
unsigned int thereBackTime = 0; //time for ping to go there and back, in microseconds
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
int distance;
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the least delay between pings
distance = sonar.ping_cm(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print (distance); // print result
Serial.println("cm");
//could use some error checking (0 = outside set distance range)
}
Challenges:
- Mount sensor to from of robot, and connect pins
- Integrate above code into your robot control code.
- Use sensor to make your robot stop if it seems an obstruction
- Proportional control: Use sensor to adjust forward speed to be proportional to distance from object