Moving DC Motor with different speeds

I recently did project 9 in the Arduino Starter Kit. It later said to hook up a potentiometer and control the speed of the motor's spin. My motor still spins with the same speed all the time. What am I doing wrong?

My code:

const int motorPin=9; const int potPin=A0; int potVal=0; int motorVal=0;

void setup() { pinMode(9, OUTPUT); Serial.begin(9600); }

void loop() { potVal=analogRead(potPin); int motorVal=map(potVal, 0, 1023, 0, 255); digitalWrite(motorPin, motorVal); Serial.print("motorVal: "); Serial.println(motorVal); delay(5);

}

Use "analogWrite" instead of "digitalWrite" for the motor speed.

 analogWrite(motorPin, motorVal);

Please read the thread "How to use this forum - please read" and learn to use code tags.

Welcome to the forum.

I hope you let us know how the motor works with the suggested change.

DuaneDegn: Use "analogWrite" instead of "digitalWrite" for the motor speed.

 analogWrite(motorPin, motorVal);

Please read the thread "How to use this forum - please read" and learn to use code tags.

Welcome to the forum.

I hope you let us know how the motor works with the suggested change.

Should I then connect the middle pin of the transistor to an analog pin and not a PWM digital pin?

nicksolo: Should I then connect the middle pin of the transistor to an analog pin and not a PWM digital pin?

I'm not looking at the transistor circuit but to read an analog input you need to use one of the analog pins. To control an analog output you need to use a PWM pin.

"analogWrite" sets the PWM duty cycle on a PWM pin. It looks like you're using pin #9 which is a PWM so you won't need to change the pin you're using.

If you're not sure where the wire from pin #9 connects with the circuit, you'd need to post the circuit you're using. I doubt this is a problem though. Just make the change suggested. If the circuit worked before, it should work with the suggested change.

I haven't read project #9 myself but I bet you're supposed to control the speed of the motor, using analogWrite is the obvious solution.