r/ArduinoProjects • • Mar 11 '24

My ultrasonic sensor not working

Post image

Hello guys, i am new here and still learning. I tried to connect my ultrasonic sensor but it never works. I tried diff codes but it never works. Sometimes it prints totally random number (like my hand is max5cm from sensor and i shake it a little and it bumps from 0 to 2000m but never shows correct data). Can i be doin something wrong or is just sensor broken ?

1 Upvotes

10 comments sorted by

2

u/Spectraman Mar 11 '24

I would start by moving the pinMode() functions to the inside of your setup() function, because now you are setting it every loop.

1

u/Article_Prior Mar 11 '24

So i changed the code but it did not change anything. I found out only data it is giving is when i move little with gnd cable, either near arduino or near sensor. But still gives random numbers

1

u/Spectraman Mar 11 '24

The rest of the code seems correct, so it could be something with the wiring. Maybe interference? Hard to tell without seeing the hardware setup.

1

u/Article_Prior Mar 12 '24

I can send you the setup to the dm but i am pretty sure the sensor is somehow damaged.

1

u/Spectraman Mar 12 '24 edited Apr 02 '24

The pictures you sent in the DM look fine, so it could actually be the sensor itself. To absolutely rule out if this is the case, I would try this:

  • Of course, if you have another sensor try that one

  • Print out the duration directly, instead of the conversion calculations

  • Use a different USB cable/port

  • Play with the baud rate

  • Try a library for this particular sensor

1

u/Article_Prior Mar 12 '24

Ok thank you for help. I ll try it when i come home. Sadly i only have 1 this sensor so not able to check it with another but ill try your points.

2

u/henriquemattosesilva Mar 11 '24

Try to change the definitions about the pinMode of ultrasonic for void setup.

pinMode(pingPin, OUTPUT);
pinMode(echoPin, INPUT);

1

u/MadManMax_123 Mar 12 '24

Move the pinMode() function under void setup()

1

u/Physical-Acadia-283 Mar 12 '24

Those “long” functions are not executing cuz once the program reaches void loop it stays there cuz its a loop, you should move them so they’re before void setup. Also, how exactly are you converting time( duration) to distance?

1

u/otieno88 Mar 13 '24

I’d move lines 9, 10, and 16 in set up. Between line 17&18, I’d insert a code stating

If (duration == null) { Serial.print(“null value detected”); }

Alternatively, you can print the value of duration before passing it to the next two methods. You can do that by writing:

Serial.print(“Duration is: “ + duration);