SR04 Ultra Sonic Sensor Issues

Hello all I hope you are all doing well today. I am in quite a bit of a pickle. I am helping my boss do an Arduino workshop this thursday and we decided object avoiding robots would be neat. We got the parts in last week and I just now had time to put together one and I am having issues.

When I connect the sensor to the Arduino it works fine. It gives me clear reads and I have no issue. Now when I put the Motor Shield on the Arduino and then connect the sensor to the Arduino the sensor will work for a little bit then stop and then it works randomly when I fiddle with the ends of the cable. I swapped cables, sensors, Arduino, and the shield and I have not had any luck. I checked the pins on the motor shield that I am connecting the sensor to and they both directly to the Arduino. The 5v and GND rails I am connecting to go directly the the Arduino aswell. I have no idea why it is doing this so if you guys have any thoughts they would be greatly appreciated.

Here is my code.

#include <NewPing.h>
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_64KHZ); AF_DCMotor motor2(2, MOTOR12_64KHZ);
NewPing sonar(9,10);
 

long duration, inches;
long distance; 
void setup() {

  Serial.begin(9600);
  Serial.println("Motor test!");
  
  motor.setSpeed(200); 
  motor2.setSpeed(200);
}
 
void loop()
{
  distance = pingMethod();
  
  if(distance >=7){
    motor.run(FORWARD);   
    motor2.run(FORWARD); 
  }
  else{
   motor.run(RELEASE);
   motor2.run(RELEASE); 
  }
}

long pingMethod(){
  
  duration = sonar.ping();
 

  inches = microsecondsToInches(duration);

  Serial.println(inches);
  return inches;
}
 
long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

How are the motors powered? Does the problem get worse when the motors are running?

The motors are currently being powered with a 9v battery. However even if I disconnect the motors and remove all of the code that relates to the motors I still have these issues. Is it possible the shield itself draws too much power? I tried it plugged into both the computer and the 9V battery and I had no success it still has the same issues.

Measure the supply voltage at the rangefinder. If it is less than 5 volts you will need better power supply. I have had trouble running those sensors from USB (4.8 volts). I now use a powered USB hub or solid 5 volt supply when using them.