// Adjust these constants to get the desired effect
const byte MIN_MOTOR_SPEED = 0;
const byte MAX_MOTOR_SPEED = 255;
const unsigned int MIN_DISTANCE_CM = 4;
const unsigned int MAX_DISTANCE_CM = 400;
void loop() {
unsigned int distance_cm = getDistance_cm();
// Check for target being out of range
if (distance_cm == 0)
distance_cm = MAX_DIESTANCE_CM;
// Constrain the distance to the practical range of the sensor
distance_cm = constrain(distance_cm, MIN_DISTANCE_CM, MAX_DISTANCE_CM);
// Map the distance range to the speed range: close->slow, far->fast
byte speed = map(distance_cm, MIN_DISTANCE_CM, MAX_DISTANCE_CM, MIN_MOTOR_SPEED, MAX_MOTOR_SPEED);
// Set the motor speed
motor1.setSpeed(speed);
}