February 23, 2011

Motor Speed Control through a PC Serial Port with arduino

Last time I showed you how to "speak" to your arduino through a serial port. Today we will use that knowledge to control a motor! About a week ago I took apart an old CD Burner and found 3 motors. I will use one of those today.

The program is very straightforward, just like yesterday we send data from the Serial Monitor in the arduino program, the board "listens and responds" to them.

Here is a video of the program running, I explain the code after that.

First a bit of theory. What is PWM (Pulse Width Modulation)? Simply put it's a way to control the speed of a motor (or the brightness of a LED), by changing the width of a pulse that you send to the device. The wider the pulse, the more energy it has so more speed for the motor (or brightness for a LED). 

And how do we do that in arduino? Using the analogWrite() function. That function has two input values. The first is the pin, in which the pulse will exit (in this example we used pin #3) and the second is a number from 0 to 255 which is the width of the pulse (0 means no width so you basically send a LOW pulse, and 255 means the width is the maximum width possible, that is you send a HIGH pulse). Anything in between is linearly adjusted (127 is half a HIGH pulse etc.) You can read more about PMW here.

So this is the code used:
 * serial_motor_control.pde
 * -----------------
 * Controls the speed of a motor depending on what is received
 * through the serial port.

 * http://spacetinkerer.blogspot.com

int input = 0;

void setup() {             
  // initialize the PWM pin #3 as an output.
  pinMode(3, OUTPUT);

void loop() {
    input = Serial.read();
    if (input == '0'){
      analogWrite(3, 0);
      Serial.println("Speed is 0!");
    if (input == '1'){
      analogWrite(3, 64);
      Serial.println("Speed is at 25%");
    if (input == '2'){
      analogWrite(3, 127);
      Serial.println("Speed is at 50%");
    if (input == '3'){
      analogWrite(3, 192);
      Serial.println("Speed is at 75%");
    if (input == '4'){
      Serial.println("Speed is at 100%");

The rest of the program is pretty similar to the previous example

One final note on the wiring of the motor. Typically a motor has two cables for input one red for positive voltage, and one black for negative voltage or ground. You connected the red wire to pin#3, or another PWM pin and the black wire to one of the ground (GND) pins.

So try the program yourself.

You can download the code here.

If you like my posts then subscribe via rss, or via e-mail to stay updated.

Happy Tinkering!

If you liked this article then take a second to bookmark it with...


  1. might want to check how much current you'll be drawing through the pin, need to power it through a transistor or FET to be safe

  2. Can only integers be inputed in the serial port?