I've got a very simple setup with an HC-SR04. I've connected the power (5V from the Arduino 5V and GND pins), and the trigger and echo pins from the HC-SR04 are connected to pins 11 and 12 of the Arduino Uno. If I use hand-written code like this:
#define trigPin 11
#define echoPin 12
float duration, distance;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the response from the HC-SR04 Echo Pin
duration = pulseIn(echoPin, HIGH);
// Determine distance from duration
// Use 343 metres per second as speed of sound
distance = (duration / 2) * 0.0343;
// Send results to Serial Monitor
Serial.print("Distance = ");
if (distance >= 400 || distance <= 2) {
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
delay(500);
}
it works great! No issues. However, the general advice around the web is to prefer NewPing. Okay. I installed NewPing from the library manager in the IDE, and tried the very simple code:
#include <NewPing.h>
#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define MAX_DISTANCE 500
// NewPing setup of pins and maximum distance
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
delay(50);
unsigned int distance = sonar.ping_in();
Serial.print(distance);
Serial.println("in");
}
which sadly does not work very well. Most of the distances printed are zero, and even if I put something large in front of the sensor, it only briefly registers it before going back to zero. I've tried increasing the delay to 500, which improves things, but there are still a lot of zeros. What would cause the hand-written code to work but not the NewPing code?