Book Image

Arduino Development Cookbook

By : Cornel M Amariei
Book Image

Arduino Development Cookbook

By: Cornel M Amariei

Overview of this book

Table of Contents (16 chapters)
Arduino Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Controlling speed with PWM


A motor that can only be on or off is not that useful. We need to control the speed of a motor using code. Sometimes, we want the motor at half speed; sometimes we want it faster and sometimes slower. However, the motor is connected to a digital pin, whose value can either be maximum or nothing. How can we make this clear 1 and 0 into something in-between? With Pulse Width Modulation or PWM.

Getting ready

Following are the ingredients needed for this recipe:

  • A DC motor

  • A resistor between 220 ohm and 4,700 ohm

  • A standard NPN transistor (BC547, 2N3904, N2222A, TIP120) or a logic-level compatible MOSFET (IRF510, IRF520)

  • A standard diode (1N4148, 1N4001, 1N4007)

How to do it…

The following are the steps to control the speed of a motor using PWM:

  1. Connect the Arduino GND to the long strip on the breadboard.

  2. Connect one of the motor terminals to VIN or 5V on the Arduino. We use 5V if we power the board from the USB port or, if we want higher voltages, we could use an external power...