run dc motor at a controlled rate using arduino and circuit components


I have just started to use an arduino so i am not very familiar with the codes.

My main goal is to run a dc motor at a controlled rate (eg.every 10seconds) using an arduino and other components such as resistors and diodes.

My main problem is that im not sure of the codes needed to run the motor at a controlled rate.i have searched google for the codes but im unable to find the ones related to my work. is the website i refered to to run the motor

This is the code i used to run the motor:

int motorPin = 3;

void setup()
pinMode(motorPin, OUTPUT);
while (! Serial);
Serial.println(“Speed 0 to 255”);

void loop()
if (Serial.available())
int speed = Serial.parseInt();
if (speed >= 0 && speed <= 255) // This if statement will prevent the user from entering invalid motor speeds
analogWrite(motorPin, speed);


Any suggestions to improve our circuit and codes?

Thank you

Not sure what you mean "at a controlled rate (eg.every 10seconds)". Do you mean you want it to start up every 10 seconds and run for some short time, or what?

The code you posted requires user to type something on the monitor as a signal to the motor: what's that got to do with the 10 seconds thing?

Any suggestions to improve our circuit...?

You didn't post your circuit.

Let's say, in a day, I want it run for 5 seconds every 8 hours at a desired speed.i am not sure of how to write the codes for the motor to run like that.

And for the circuit, it is in this website : Control a 5V Motor with the Arduino - Make:

Thanks for the reply anyways

Well the easiest way is to use the delay() approach as shown in Blink. It's ugly though, since it blocks the sketch from doing anything else while it's caught in a delay(), but if that's all you want your sketch to do, it will work.

Better though, is to use the delay()-less approach of millis() as shown in BlinkWithOutDelay.

In either case, think of the LED as the base of the transistor.

You should post a circuit diagram and not expect responders to go digging around on another site looking for details.

Post the circuit YOU are using, including exact details of all the components and the motor. As far as I can see that website you point to doesn't give a real circuit diagram or component details and is therefore useless to anyone who hasn't bought their kit.

Your code has no attempt at timing but it does set the motor speed from user input. Do you want the user to set speed? Do they have to input a value every 8 hours to set the speed for the next 5 seconds? Or what and when? Details are important in programming.


You need to explain what "controlled rate" means. Perhaps you could tell us what you are doing
with the motor.