HC-SR04 Fluctuation of Values for fast refresh rates

I am trying to use a gps neo 6m in parallel with the hcsr04 and I have a bit of a problem. I get periodically wrong measurements and I have tried to change many aspects of the code but can't seem to find a solution. I need helpsketch_oct29a.ino|attachment (2.2 KB) The D Column is the Distance.

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#define echoPin 14
#define trigPin 15
File myFile;
int RXPin = 3;
int TXPin = 2;
int GPSBaud = 9600;
TinyGPSPlus gps; 
long duration; 
int distance;
int distance2;
// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup()
{
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  gpsSerial.begin(GPSBaud);
  
myFile = SD.open("test.txt", FILE_WRITE);
if(myFile){
myFile.println("New Test Began...");
myFile.println(" ");
myFile.println(" ");
myFile.close();
}else {
    Serial.println("error opening test.txt");
  }
}

void loop()
{  
  while (gpsSerial.available() > 0){
    
    if (gps.encode(gpsSerial.read())){
      displayInfo();
      
    
    }
  if (millis() > 6000 && gps.charsProcessed() < 10)
  {
    Serial.println("No GPS detected");
    while(true);
  }
  
 
  }
}

void displayInfo()
{
  myFile = SD.open("test.txt", FILE_WRITE);
  if(myFile){
  if (gps.location.isValid())
  {delay(500);
    myFile.print(gps.location.lat(), 6);
    myFile.print(",");
    Serial.println(gps.location.lat(), 6);
    myFile.print(gps.location.lng(), 6);
    myFile.print(",");
    myFile.print(gps.speed.kmph());
    
    distance2=distance;
    digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2; 
  myFile.print(",");
    myFile.print(distance);
    Serial.println(distance);
  if((distance2-distance)>20){
    myFile.print(",");
    myFile.println("1");
    }else{
      myFile.print(",");
      myFile.println("0");
      }
  
  }
  else
  {
    Serial.println("Location: Not Available");
  }
   
   myFile.close();
  }else {
Serial.println("error opening test.txt");
}
}```

Try slowing the ping rate to no more than about 20Hz.

where exactly should i place the delay(20);??

That would be 50Hz :wink:

my bad delay(50) but where should i place it, at the gps refresh rate or at the sonar?

Oops, sorry, just noticed the delay(500).

Scratch that.

Check your power supply and decoupling.

Also, please use the auto format tool in the IDE before posting code.