Small DC Motor with an Arduino – Part 2

PWM Speed Control

Small DC Motor PWMGenerally you can control the speed of a DC motor by tweaking the voltage.  The higher the voltage, the high the speed.  Conversely, lowering the voltage slows things down.

In the case of a 5 volt DC motor,  applying 5V volts to the motor would give us full speed, while 2.5 volts would give us a slower speed.   Indeed, back in the day,  a simple potentiometer as part of a voltage divide would often be used to do apply a variable voltage to the motor directly.

In the age of micro-controllers however,  the most common method of controlling DC motor speed is to use Pulse Width Modulation (PWM).

With an Arduino, we use pins capable of providing a pulse width modulated output and we use a function called analogWrite to control the amount of time the motor is on.

Fundamentally, we specify the percentage of time the motor will see a full 5V and the amount of time it will see zero volts.   Thus a motor that is on 80 percent of the time would see an average of 4 volts.

Similarly, a motor that is on 20 percent of the time would see an average of 1 volt.

Using the Arduino analogWrite Command

Once we’ve set the pinMode to Output, its just a matter of using the analogWrite command to specify how much time we want the output on to create an average DC voltage to supply to the motor.

It will look like this:

AnalogWriteIn the example above,  I’ve chosen 204 as the amount time I want the output on… which is about 80 percent of the time.

The Parts and Hook Up.

You’re going to use the same hookup found  in Simple DC Motor with an Arduino – Part 1.

The Arduino PWM Motor Code

// Henry's Bench Small DC Motor with PWM
int motorDrive = 3; // The output to the transistor that drives the motor
int timeOn = 2500; //amount of time motor is on
int timeOff = 1000; //amount of time motor is off
void setup()
{
 pinMode(motorDrive, OUTPUT); 
}
void loop() // run over and over again
{
 analogWrite(motorDrive, 255); // Top Speed
 delay(timeOn); // number of milliseconds to keep on
 analogWrite(motorDrive, 128); // Lower Speed
 delay(timeOff); // number of milliseconds to keep off
}

Add a Comment

Your email address will not be published. Required fields are marked *