Skip to content

Instantly share code, notes, and snippets.

@GreenMoonArt
Last active July 21, 2016 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreenMoonArt/4eb1dbe3ca9e0ef33d6aa28b3c5c9f0c to your computer and use it in GitHub Desktop.
Save GreenMoonArt/4eb1dbe3ca9e0ef33d6aa28b3c5c9f0c to your computer and use it in GitHub Desktop.
// Install NewPing library: https://bitbucket.org/teckel12/arduino-new-ping/downloads/NewPing_v1.7.zip
// https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home
/* YourDuino Basic Robot Kit V2: Ultrasonic Sensor Test
- WHAT IT DOES
- Tests the operation of the Ultrasonic Sensor
- SEE the comments after "//" on each line below
- CONNECTIONS: (suggest cable with 4 wires: Red,Orange,Yellow,Green )
- Sensor Vcc to RoboRED Vcc (Red)
- Sensor Ground to RoboRED Gnd (Green)
- Sensor Trig to RoboRed pin 2 (Orange)
- Sensor Echo to RoboRED pin 3 (Yellow)
- V2.10 11/10/2014
Note: The sketch will send the distance measurements it is making to the "Serial Monitor," which is a window you can start by
clicking on the "serial monitor" icon at the upper right of the IDE window. Put your hand or other object in front of the Ultrasonic
sensor and move it farther and closer and you should see the distance displayed on the Serial Monitor.
Questions: terry@yourduino.com */
/*-----( Import needed libraries )-----*/
#include <NewPing.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define TRIGGER_PIN 2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 3 // 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.
/*-----( Declare objects )-----*/
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
/*-----( Declare Variables )-----*/
unsigned int uS;
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
//NONE
//*********( THE END )***********
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment