AF_DCMotor Class

The AF_DCMotor class provides speed and direction control for up to four DC motors when used with the Adafruit Motor Shield.  To use this in a sketch you must first add the following line at the beginning of your sketch:
#include <AFMotor.h>

AF_DCMotor motorname(portnum, freq)

This is the constructor for a DC motor.  Call this constructor once for each motor in your sketch.  Each motor instance must have a different name as in the example below.
  • port num - selects which channel (1-4) of the motor controller the motor will be connected to
  • freq - selects the PWM frequency.  If no frequency is specified, 1KHz is used by default.
Frequencies for channel 1 & 2 are:
  • MOTOR12_64KHZ
  • MOTOR12_8KHZ
  • MOTOR12_2KHZ
  • MOTOR12_1KHZ
Frequencies for channel 3 & 4 are:
  • MOTOR34_64KHZ
  • MOTOR34_8KHZ
  • MOTOR34_1KHZ
AF_DCMotor motor4(4); // define motor on channel 4 with 1KHz default PWM
AF_DCMotor left_motor(1, MOTOR12_64KHZ);  // define motor on channel 1 with 64KHz PWM
Note:  Higher frequencies will produce less audible hum in operation, but may result in lower torque with some motors.


Sets the speed of the motor.
  •   speed- Valid values for 'speed' are between 0 and 255 with 0 being off and 255 as full throttle.
  motor1.setSpeed(255);  // Set motor 1 to maximum speed
  motor4.setSpeed(127);  // Set motor 4 to half speed 
Note: DC Motor response is not typically linear, and so the actual RPM will not necessarily be proportional to the programmed speed.


Sets the run-mode of the motor.
  • cmd - the desired run mode for the motor
Valid values for cmd are:
  • FORWARD - run forward (actual direction of rotation will depend on motor wiring)
  • BACKWARD - run backwards (rotation will be in the opposite direction from FORWARD)
  • RELEASE - Stop the motor.  This removes power from the motor and is equivalent to setSpeed(0).  The motor shield does not implement dynamic breaking, so the motor may take some time to spin down

delay(1000);  // run forward for 1 second;
delay(100);  // 'coast' for 1/10 second;  // run in reverse
Last updated on 2015-11-18 at 11.31.35 AM Published on 2012-07-29 at 11.58.37 AM