Control a Stepper Motor With PWM

by StepsoftheSun in Circuits > Electronics

40713 Views, 111 Favorites, 0 Comments

Control a Stepper Motor With PWM

IMG_20161213_110826.jpg
IMG_20161213_100036.jpg

Ever wanted to control several stepper motors precisely with just one microcontroller? Use PWM! Instead of bit-banging and writing your own delay functions to create square waves, you can use the builtin timers and pin-change interrupts available on most hobbyist microcontrollers.

In this case we'll use a Teensy LC, a Pololu DRV8825 driver and a NEMA 17 stepper motor.

Wiring and Connections

IMG_20161213_095413.jpg
IMG_20161213_095503.jpg
Screen Shot 2016-12-13 at 10.17.35 AM.png
Screen Shot 2016-12-13 at 11.31.59 AM.png

First solder headers to your DRV8825 board and Teensy, then put them on a breadboard. (It's actually easiest to solder these headers while the boards are already on a breadboard, but work in whatever order you'd like!)

We will connect the stepper driver much like the diagram from Pololu's product page (also included in the image below).

  • VMOT and GND will have a 100uF capacitor between them and be connected to a 12V benchtop supply capable of supplying at least 2A.
  • The ~RESET and ~SLEEP pins will be held high by connecting them to the teensy's 5V rail.
  • The stepper itself will connect to A1, A2, B1 and B2.
  • Set the stepper into 1/16 step mode by pulling M2 high and allowing M0 and M1 to float.
  • The driver's GND pin will connect to the teensy GND.
  • The teensy's pin 2 will connect to the driver's DIR pin.
  • And the teensy's pin 3 will connect to the driver's STEP pin.

The teensy will have one additional connection: pin 9 will be tied to pin 3. This will allow the teensy to count pulses via a pin-change interrupt.

Also make sure to set the DRV8825's current limiting resistor to an appropriate value, as described on their product page.

Coding!

Screen Shot 2016-12-13 at 11.18.33 AM.png
Screen Shot 2016-12-13 at 11.18.45 AM.png
Screen Shot 2016-12-13 at 11.19.10 AM.png
Screen Shot 2016-12-13 at 11.22.51 AM.png
Screen Shot 2016-12-13 at 11.23.26 AM.png
Screen Shot 2016-12-13 at 11.23.35 AM.png
controlling a stepper motor with PWM

I used teensyduino to write a little arduino-like sketch to control the stepper motor. Follow the teensyduino setup steps here to get your coding environment setup correctly.

The code will allow us to send a command from the terminal to control the stepper's position. The full sketch is posted here. Each image below will breakdown a section of the code. And there's also a quick demo of the controller in action!

What's Next..

Some things you could try next:

  • add limit switches to control the max and min extent of the stepper's travel
  • experiment with acceleration to get the stepper quickly up to speed
  • try different microstepping values -- the DRV8825 supports full step to 1/32 microsteps

If you try any of these, post your results in a comment below!