Basic Robotics Help. Variable motor speed control by ultrasonic sensor input on arduino
You may have discovered not all pins can do PWM, and the Arduino "IDE" doesn't tell you. AnalogWrite a value larger than 0 and it's 100% on.

Write a test sketch that steps the pin through 25%, 50%, 100% and check that it works at all.

Then, try to get some equations going for the motor control; . Have three regions, selected by an If statement:


distance > 100 : full speed
distance &lt; 20 : stop
20 &lt; distance &lt; 100 : speed=3*(distance-20)


edit Not So Undocumented... the AnalogWrite page says


  On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.


edit2 seems pin 9 should work on almost any Arduino. Perhaps your problem is in the transistor circuit.