Need help with controlling Dc motor using Range sensor SR04 and a push button.

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 . Please help me with this.

I used 1.5-3v DC motor, 220 ohm resistors (i think or it might be 10k?) using 5v pin from the arduino (is this bad for the motor?)

#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);
}

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

You set motorpin as output but didn't assign whether it will output HIGH or LOW? Any reason?

liudr:
You set motorpin as output but didn't assign whether it will output HIGH or LOW? Any reason?

Hi thanks for the reply, i saw a tutorial online regarding dc motor, and they used analogWrite() to set the speed of the motor. I think setting it as HIGH would run the motor at maximum speed? is that right?

It seems like you hooked up the motor directly to +5V AND ground. It's a bit hard to be certain from the picture. Try disconnecting the jumper from pin 8. If the motor still goes, then that's most likely your problem.