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.
This is my code:
#include <Ultrasonic.h>
const int alarmPin = 7;
const int alarm2Pin = 6;
Ultrasonic ultrasonic(9,8,5000); // (Trig PIN,Echo PIN, Max.TimeOut in µsec )
Thanks alot AWOL!!! now its working. The serial monitor still showing the 0cm, but at least they don't interfere in the function of my proyect. The led stays on. Thanks alot.
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.
#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);
}
This fixes your script and will show the correct distance on the serial monitor (make sure you set the serial speed to 9600 baud).