Hello. Absolute Arduino newbie here. I'm making a miniature autonomous tunnel drilling machine project for uni which requires the use of an ultrasonic sensor. Prior to adding an ultrasonic sensor, I have successfully controlled the speed and direction of two motors (one for the drill, the other for the conveyor belt) for the machine. In order for the machine to be autonomous, I need the motors to be activated when an obstacle is detected ahead (within a certain range of distance) of the machine by the ultrasonic sensor.

I've been trying to test out my HC-SR04 sensor which I intend to use to run one 9V DC motor and another 12V DC motor using the L298N motor driver module by following several tutorials on YouTube. After failing multiple times running the 9V motor with the sensor, I removed all components excluding the sensor to test the sensor solely. It turns out that the sensor simply does not work when the VCC pin is connected to the 5V power pin (output shown on the serial monitor is constant 0's), but i realized it works just fine when connected to the VIN power pin. I've tried using either the USB or a 9V battery as a power input but the problem remains.

I need the sensor to successfully run using the 5V power pin because in order to run the two motors, the +5V pin from the L298N module also needs to be connected to the VIN pin on the Arduino Uno. Is there any solution to this? I'm getting quite frustrated. The code and schematic of my circuit are inserted below. Thanks in advance!

int trigPin = 10;
int echoPin = 11;
int pingTravelTime;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pingTravelTime = pulseIn(echoPin, HIGH);
  delay(25);
  Serial.println(pingTravelTime);
}

Testing only the sensor:

The output:

I don't see pretty much issue with your code just try adjusting delay for turning trigpin low for few micros

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pingTravelTime = pulseIn(echoPin, HIGH);
  int distance = pingTravelTime* 0.034 / 2;
  delay(25);
  Serial.println(distance);
}

I am not pretty sure this change will help .The cause probably damaged hc-sr04 if you have a spare then test it out