DC motors are used for all sort of robotic projects.

The Motor HAT can drive up to 4 DC motors bi-directionally. That means they can be driven forwards and backwards. The speed can also be varied at 0.5% increments using the high-quality built in PWM. This means the speed is very smooth and won't vary!

Note that the H-bridge chip is not meant for driving continuous loads over 1.2A or motors that peak over 3A, so this is for small motors. Check the datasheet for information about the motor to verify its OK!

Connecting DC Motors

To connect a motor, simply solder two wires to the terminals on the motor (if they're not already there!) and then connect them to either the M1, M2, M3, or M4 terminal blocks on the Pi hat. If your motor is running 'backwards' from the way you expect, swap the wires in the terminal block

For this demo, please connect it to M1.

Run python3 to get to the Python REPL.

Controlling DC Motors

To demonstrate the usage, we'll initialise the library and use Python code to control a DC motor from the Python REPL.

First you'll need to import and initialize the MotorKit class.

from adafruit_motorkit import MotorKit
kit = MotorKit()

The four motor spots on the Pi hat are available as motor1, motor2, motor3, and motor4.

In this example we'll use motor1.

Now to move a motor you can set the throttle attribute. We don't call it speed because it doesn't correlate to a particular number of revolutions per minute (RPM). RPM depends on the motor and the voltage which is unknown.

For example to drive motor M1 forward at a full speed you set it to 1.0:

kit.motor1.throttle = 1.0

To run the motor at half throttle forward use a decimal:

kit.motor1.throttle = 0.5

Or to reverse the direction use a negative throttle:

kit.motor1.throttle = -0.5

You can stop the motor with a throttle of 0:

kit.motor1.throttle = 0

To let the motor coast and then spin freely set throttle to None.

kit.motor1.throttle = None

That's all there is to controlling DC motors with the Adafruit CircuitPython MotorKit library! With DC motors you can build fun moving projects like robots or remote controlled cars that glide around with ease.

Full Example Code

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""Simple test for using adafruit_motorkit with a DC motor"""
import time
import board
from adafruit_motorkit import MotorKit

kit = MotorKit(i2c=board.I2C())

kit.motor1.throttle = 1.0
kit.motor1.throttle = 0

This guide was first published on Jan 27, 2015. It was last updated on Jan 27, 2015.

This page (Using DC Motors) was last updated on Oct 01, 2023.

Text editor powered by tinymce.