- Wed Dec 10, 2014 1:00 am
#177553
Hello! The US 100 Ultrasonic will be used to detect the presence of an object in just a range of 3 inches. It should be displaying a 1 if an object is detected and 0 if otherwise. I modified the codes from someone but unfortunately, it doesn't work the way it was supposed to be and I'm having a hard time trying to find out what went wrong. I hope someone can help me. Thank you. Below would be the codes and the printscreen of the output.
Code: Select all
/*-----( Import needed libraries )-----*/
#include <NewPing.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define TRIGGER_PIN 11
#define ECHO_PIN 10
#define MAX_DISTANCE 14 // 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 )-----*/
int DistanceIn;
int DistanceCm;
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(9600);
Serial.println("UltraSonic Distance Measurement");
Serial.println("YourDuino.com terry@yourduino.com");
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
DistanceIn = sonar.ping_in();
Serial.print("Ping: ");
Serial.print(DistanceIn); // Convert ping time to distance and print result
// (0 = outside set distance range, no ping echo)
Serial.print(" in ");
delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
DistanceCm = sonar.ping_cm();
Serial.print("Ping: ");
Serial.print(DistanceCm);
Serial.println(" cm");
if ( (DistanceCm <= 7) && (DistanceCm != 0) )
{
Serial.println("1");
}
else if ( (DistanceCm > 7) && (DistanceCm !=0) )
{
Serial.println("0");
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
// None
//*********( THE END )***********