A DC motor is one of the basic elements of a maker’s toolbox. Whether you’re driving autonomous robots or spinning a cooling fan, a DC motor is a relatively simple way to accomplish your task! In this sample, we’ll use pulse-width modulation (PWM) to vary the speed of a motor.
You will need:
Motors draw more current than the pins on the Raspberry Pi 2 or 3 can safely provide. Therefore, we’ll use a transistor to connect the motor to an external power source. Transistors are like switches; when we give it a small amount of current, it can enable the flow of a much larger current. For our motor, we used a 5v DC adapter that supplies at least 1A of current. It is OK to use an adapter with more current capacity than your motor needs; as the adapter should only supply what is needed by the motor.
We are also using a diode to protect the PCA9685 board and the Raspberry Pi from backflow current that can damage the hardware. Diodes enable power flow in one direction only.
We highly recommend you use the PCA9685 PWM controller. You can use either the hat or the breakout board, but this board is directly supported by Microsoft and will offer the best experience.
Additionally, the controller should not have any I2C hardware address pins set. Below is an image of the I2C pins on the PCA9685 PWM controller, where none of the pins are set (and therefore hardware I2C address is the default 0x40).
Refer to the fritzing diagram below to hook up your motor and PWM controller.
The PCA9685 PWM Controller should be connected as follows:
Refer to the fritzing diagram above for the remaining circuit connections.
Replace the existing code in your main .ino file with the following code:
Press F5 to build and deploy your project.
Refer to the Arduino Wiring Project Guide for more instructions on how to deploy your app!
The motor should run at max speed for 3 seconds, off for 3 seconds, and then perform an acceleration from a stopped state to maximum speed and back again. The motor will then stop for one second before starting all over again!
Refer to the Arduino Wiring Porting Guide for common issues and concerns when working with Arduino Wiring sketches.
Your session has expired. Please sign-in again to continue. Unfortunately any unsaved changes will be lost.