Control DC motor speed with ultrasonic sensor

i want to make a code where the ultrasonic sensor can adjust the speed of the DC motor according to the distance (the farther the faster and the closer the slower). But I don't know where to put the code or how. In my code I tried to use a potentiometer and it worked. I want to replace the potentiometer with an ultrasonic sensor. Anyone can help me?

int pinPot = A0;
int nMotor1;
int nMotor2;
int nPot;
int Motor1 = 6;
int Motor2 = 5;
int pinButton = 2;
int dir1 = 4;
int dir2 = 7;
int stat;

void setup() 
{
  pinMode(Motor1, OUTPUT);
  pinMode(Motor2, OUTPUT);
  pinMode(pinPot, INPUT);
  pinMode(pinButton, INPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);
  
}

void loop() 
{
  stat = digitalRead(pinButton);
  if(stat == LOW)
  {
    digitalWrite(dir1, LOW);
    digitalWrite(dir2, HIGH);
  
  }
  else
  {
    digitalWrite(dir1, HIGH);
    digitalWrite(dir2, LOW);
  
  }
  nPot = analogRead(pinPot);
  nMotor1 = map(nPot, 0, 1023, 0, 255);
  nMotor2 = map(nPot, 0, 1023, 0, 255);
  analogWrite(Motor1, nMotor1);
  delay(1);
  analogWrite(Motor2, nMotor2);
  delay(1);

}

Okey. Is it correct that Your potentiometer code runs well?
Then I suggest that You make a little code that is only reading the distance sensor and printing to Serail Monitor. Then You know how the distance sensor is working. Converting sensor readings to motor control will then be easy.

You are already using the map() function. Once you know what numbers you get with the rangefinder, with the program suggested by Railroader, you can replace the pot values in the map() function.

okay i'll try. I won't use serial monitor, should i still use the serialprint etc. ?