Arduino Ultra Sonic Sensor always returns 0 -


i doing basic project in arduino uno connecting ultra sonic sensor (hc-sr04) should print in serial monitor distance of closest object print 0.

this code:

long distance; long time;  void setup(){   serial.begin(9600);   pinmode(4, output);    pinmode(2, input);  }  void loop(){   digitalwrite(2,low);   delaymicroseconds(5);   digitalwrite(2, high);   delaymicroseconds(10);    time = pulsein(4, high);   distance = int(0.017*time);     serial.print("distance: ");   serial.print(distance);   serial.println(" cm.");   delay(1000); } 

and breadboard:

enter image description here

the primary issue see code doesn't match wiring diagram.

for example, diagram shows trig connected pin 4. trig should output arduino have defined input.

the echo connected pin 2 , should input, have defined output.

finally, in loop(), not using pin 2 or pin 4, pins 9 , 8. issue timing use in setting trigger pulse - not match datasheet. (assuming connected pins shown in diagram):

#define sensortrigpin    4 #define sensorechopin    2  void setup() {     serial.begin(9600);     pinmode(sensortrigpin, output);     pinmode(sensorechopin, input); }  void loop() {     int pulsewidth = 0;      digitalwrite(sensortrigpin, high);     delaymicroseconds(10);     digitalwrite(sensortrigpin, low);      pulsewidth = pulsein(sensorechopin, high);      serial.print("pulse width: ");     serial.print(pulsewidth);     delay(1000); } 

note pulsewidth amount of time takes beginning of echo pulse going high end of same pulse (when goes low). still have calculate distance based on value of pulsewidth.


update based on recent edit question

if change portion of loop() code this, should work:

void loop(){     digitalwrite(4, high);   //was (2, low)     delaymicroseconds(10);   //was (5)     digitalwrite(4, low);    //was (2, high)     //removed delay      time = pulsein(2, high);  //was (4,high);     ...  //keep rest of code same. }  

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -