Help with controlling 1.5/3v DC Motor using push button and

Hi, I previously use the switch to turn a LED on, base on the distance measured from the SR04 sensor and when press the button again it turns off the LED regardless of the distance.

I am replacing the LED with the motor and change the digitalWrite to AnalogWrite(motor, 50) to slow down the speed of the motor.

However, as soon as I hook up the motor, it spins at max speed right away without me doing anything else. Am I allow to do this? or would I have to do something when using the dc motor instead of the LED?

#define trigPin 12
#define echoPin 11
#define on_button 9
#define motorPin 8

int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on

void setup() {

Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(on_button, INPUT);
 pinMode(motorPin, OUTPUT);
}

void loop(){

val = digitalRead(on_button); // read input value and store it

// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}

old_val = val; // val is now old, store it

long distance, duration;
 digitalWrite(trigPin, LOW);  
   delayMicroseconds(2); 
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10); 
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration/2) / 29.1;
   
if (state == 1 && distance > 3) {
 
   
   analogWrite(motorPin, 50); // turn motor ON
} else {
analogWrite(motorPin, LOW);
}
 Serial.print(distance);
 Serial.println(" cm");
 delay(500);
}

https://fbcdn-sphotos-d-a.akamaihd.net/ … cd63a9bf71

I followed this to hook up the motor: (sry i dont know how to make a schematic like this for the above set up)

http://oi59.tinypic.com/2jb0cjl.jpg

Thanks a lot for your help.

Circuit is OK. Pin 8 is not a pwm pin. Suggest you swap 8 and 9 as 9 is pwm. One possibility is that the transistor is shorted, i.e. bad, you might try replacing it. In setup you can analogWrite(motorpin,0) to ensure motorpin is low.