Ultrasonic sensor and PWM

Hi,
I'm preparing a project where an ultrasonic sensor changes the rotation speed of the dc motor, depending on the distance.
There are five distances at which the motor should stop rotating, according to the figure we defined in the code language.
For some reason in the measurements I get a correct measurement distance. At a measurement of about 20 cm, the measurement jumps to 1189 cm, and because of this, the engine activity is disrupted.

I would appreciate your assistance.
This is the code:

long duration; // The time it took for the supersonic pulse to return
int distance; // the distance
#define U_trig 8
#define U_echo 9
#define  m_1 10
#define  m_2 11
#define  L_ 28 // Conveyor length

#define loc0 4
#define loc1 11.5
#define loc2 9
#define loc3 6
#define loc4 7

float location[] = {loc0,loc1,loc2,loc3,loc4,};  // The desired distance of the package from the sensor in cm, where I want the motor to stop. There should be five places

 void setup()
 {
pinMode (U_trig, OUTPUT);
pinMode (U_echo, INPUT);
pinMode (m_1, OUTPUT);
pinMode (m_2, OUTPUT);
Serial.begin(9600);
 }
 
 void loop()
 {
  move(location[20]);

}

void ultrasonic() {

digitalWrite(U_trig, LOW);
delayMicroseconds(2);
digitalWrite(U_trig, HIGH);
delayMicroseconds(10);
digitalWrite(U_trig, LOW);
duration = pulseIn(U_echo, HIGH); // Pulse repetition time in microseconds
distance = duration*0.034 / 2; // distance In cm
Serial.print("distance is: ");
Serial.println(distance);
}



void move (float location)
{
  float pre = 0.5;  // the degree of accuracy required
  int speed;
  float delta;
  do
  }
    ultrasonic();  // Current distance check
    delta= location-distance;
    if (delta<pre)
     {
      speed=map(delta,pre,L_,30,255);
      digitalWrite(m_1, LOW);
      analogWrite(m_2, speed);
      Serial.println(speed);
      delay(1000);;
     }
    else
    {
      speed=map((-delta),pre,L_,30,255);
      digitalWrite(m_1, HIGH);
      analogWrite(m_2, 255-speed);
    }
  } while (delta  > pre || delta < -pre);
}

Doesn't compile, your '}' after the 'do' should be a '{'.
Your problem may have something to do with(from the Arduino reference):

The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.

That may be giving you unexpected results.

Hi, @mk123459876
Welcome to the forum.
Thanks for using code tags. :+1:

What model Arduino are you using?

Have you looked at the NewPing library for your ultrasonic unit?

It will simplify your measurements.

Tom... :smiley: :+1: :coffee: :australia:

Checked with the code OP is missing that