DISTANCE MEASUREMENT WITH SR04 USING ALANOG PINS

GETTING DISTANCE (CM) VALUE ZERO ALWAYS

#include <AFMotor.h>
//#include <Servo.h>
#include <NewPing.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE_POSSIBLE 1000
#define MAX_SPEED 150 //
#define MOTORS_CALIBRATION_OFFSET 3
#define COLL_DIST 20 //the object is 20cm away from the sensor, this is defined to be the collision distance
#define TURN_DIST COLL_DIST+10 //we need to give the vehicle some allowance infront of it so that it may turn without bumping into obstacles. The distance of safe turn is 30cm away from obstacle
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE_POSSIBLE);

int readPing() {
delay(70);
unsigned int uS = sonar.ping(); //activating the sonar, it emits Ultrasound at 40kHz (Spd of Sound = 340 m/s or 0.0034cm/uS (microsecond))
int cm = uS/US_ROUNDTRIP_CM; //uS is asigned a value by the .ping function, which returns the time taken for soundwave to reach object and return to it
return cm; //we take that time and divide it by the time taken per centimeter in order to get 2xdistance, in cm, of object away from Ultrasonic sensor
}

OK this is some code. Not compiling as it is not a complete sketch.

I can see no questions at all. So I can't give any answers .

Why not use sonar.ping_cm() to get centimeters directly?

If you failed to wire the pins correctly that could cause it to return 0.

#define MAX_DISTANCE_POSSIBLE 1000

I'd be surprised if the HC-SR04 could reach 5 meters, let alone 10 (1000cm).

Thanks
Using sonar.ping_cm() now i am getting some value but its not giving values as on digital pins

Hi narender,

if other forum-members should really help -you have to give more informations. Nobody here has glas-sphere to look through to see the following things:

the microcontroller-board you are using
the code that you are using
the measured values on digital
the measured values on analog pins
the real physical distance measured

You should follow some rules to get better help.

If you want to post code use the insert code-Button. This butto looks like this: <|>. You can find this button if you use the reply-function instead of the quick-reply function. If you click on reply you get a menu right above the textinput-field
at the left end of this menu you wil finde the <|>-Button.

Code in such a code-section is written in a constant-distance-font which will show all the indentions the same way as in the IDE. And with a simple click the users can put the whole code into the clipboard.

best regards Stefan

It’s apparently NOT a problem with using A4 or A5. This sketch works fine for me when pointing at a good reflector.

#include <NewPing.h>


const byte TRIGGER_PIN = A4;
const byte ECHO_PIN = A5;
const unsigned MAX_DISTANCE_POSSIBLE = 500;


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE_POSSIBLE);


void setup()
{
  Serial.begin(115200);
}


void loop()
{
  Serial.println(sonar.ping_cm());
  delay(500);
}