I am having an issue with a Parallax sensor and NewPing

Continuing the discussion from NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7:

I modified your simple ping code with a Parallax sensor to trigger a media player on a laptop when someone approached the sensor within 5'. This all worked well under bench tests, but now that we have built our kiosk we are only reading 'Ping = 0cm' on the serial port and our video is triggering because the reading is less than the call in the 'if' statement. What could be the issue with reading '0 cm' from the sensor? We have tried multiple sensors, cables and digital pins on the Leonardo. Below is the code, but this all worked on our bench test system.

#include <NewPing.h>
#include <Keyboard.h>


#define PING_PIN  11  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(PING_PIN, PING_PIN, MAX_DISTANCE); // NewPing setup of pin and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(600);                     // Wait 1s between pings. 
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

Keyboard.begin();
 //if (sonar.ping_cm()> 20)
  //{ 
  //Keyboard.press('A');
  //delay(100);
  //Keyboard.release('A'); 
  //delay(14000);
  
 if (sonar.ping_cm()<= 150){ 
  Keyboard.press('D'); 
  delay(100);
  Keyboard.release('D');
  delay(14000);
 } 
Keyboard.end();
}
//
1 Like

Good of you to use code tags. Could you post an image or two of your project wired together and running the not working code?

I will take pictures once we are back at the shop tomorrow morning. I did try different pins on the Leonardo and different USB cables and wiring to the ping sensor. I did not, however, try a different Arduino. It's puzzling because this code worked on the bench. I commented out some code we tried and ultimately didn't use. I'll clean all that up once we get this working.

Sorry all, this took a little while due to some other projects getting in the way. I did figure out my problem with the Ping sensor and the NewPing library. This fix actually had nothing to do with the code or or the library. That all worked as designed and once fixed we were up and running with 6 kiosks.
The issue, as it turns out, was an intermittent connection from the 'terminal shield' that mates with the Leonardo. The Leonardo was placed into a clear plastic case and the small lid on the case was just thick enough to cause some intermittent connections. We just removed the lid and everything worked as planned. See photo below showing the terminal shield.