My ultrasonic sensor (HC-SR04) don't works. It always print 0 cm not matter what I put in front of it. I've checked the trig pin and I can confirm that it is sending signals.
My code:
int trig = 3;
int echo = 2;
int pie = 4;
double cm;
int dur;
void setup()
{
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(pie, OUTPUT);
}
void loop()
{
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
dur = pulseIn(echo, HIGH);
cm = dur * 0.034 / 2;
if (cm <= 200){
tone(pie, 262, 500);
}
Serial.println(cm);
delay(200);
}
Have you looked at the NewPing library to make things easier?
Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.
Well, we're not seeing how you have connected your circuit, but I can already make a bet.
If you take a look at the pulseIn() function docs, you'll see that it returns an unsigned long result. That means your variable dur cannot be of "int" type.
Moreover, when you do this:
you're making a floating point operation. So, if you want a better precision, make cm of float type.
I know that problem, I encoutered it many times when I used SR04 sensors. The problem is it sometimes "stucks" returning a zero value, until you "reset" it (or switch the power). My opinion is the HC-SR04 is rubbish they're very, very often faulty, and that's the reason I ceased to use it years ago, switching to the more reliable HY-SRF05. If possible, do the same!
PS: just as a side note and for confirmation, 5 years ago I wrote a small library called SRF05 to manage ultrasonic sensors, and included a "workaround" for SR04 (read the english readme, README_EN.txt), if you want to give it a try and keep using SR04, you just need to enable this feature by simply setting "Unlock=true;", as shown in the library examples.
It works now, and I think the reason is because my wiring is not attach tightly. I also changed an Arduino Board. Also, during the reading, sometime it goes like 8.98, to 3000 real quick then go back to the normal reading, which my teacher told me it's normal.
Cheers! Ordered a few of those and going to take your library for a spin once the sensors arrive. I, too, have found the HC-SR04 to be unreliable often enough that I remember and hope to improve a couple of my props with the upgrade.