Neonz:
Hello, I have a big problem and I need help. I'm trying to use the Ultrasonic Sensor HC-SR04 to make a project, I have this sensor connected to the arduino via USB and the problem is that i get multiple values of 0cm. For example i mesure 3cm, 4cm, 4cm, 5cm, 0cm,0cm,0cm,0cm, 6cm, 0cm,0cm,0cm, 8cm. I tried with the Newping library and with another library called Ultrasonic but it was the same. Something awkward is that when i use the Ultrasonic Library with the example code, it works great. But when i upload my example the problem starts.
I can't really help with someone else's library, but I do see why it's not working for you. Use the following script with my NewPing library and then if there's still a problem I can diagnose it for you:
#include <NewPing.h>
#define alarmPin 7
#define alarm2Pin 6
#define TRIGGER_PIN 9 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 8 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600);
pinMode(alarmPin, OUTPUT);
pinMode(alarm2Pin, OUTPUT);
}
void loop() {
unsigned int cm = sonar.ping_cm(); // Send ping, get ping distance in cm.
Serial.print(cm);
Serial.println(" cm");
if (cm >= 10) {
digitalWrite(alarmPin, HIGH);
} else {
digitalWrite(alarmPin, LOW);
}
if (cm < 10 && cm > 5) {
digitalWrite(alarm2Pin, HIGH);
} else {
digitalWrite(alarm2Pin, LOW);
}
delay(100);
}
That script should be a drop-in replacement using NewPing for your defective script. Let me know what happens.
Tim