Trying to control DC motor speed with PID
PID- or any similar control needs 


set point
actual value
controlling variable (your PWM value)


The difference between set point and actual variable and its change over time are combined to calculate the controlling variable in order to minimize that difference.

Control theory in general is too complex to answer the "how to" here in general.

Besides measuring the actual value you also need knowledge about the behavior of your system: e.g. If you change the PWM value from 50 to 100, how much and how quick will the motor speed change? Even the response form over time will affect the optimal parameters for your control loop. It's called (feedback) loop because any change of the PWM value will change that difference and lead to a different new value of the controlling PWM value again (Allowing for instable behavior in case of bad controlling parameters).

Getting the actual value is your first task. How your distancefonction affects the desired value (set point) might also need more clarification...