From the course: Raspberry Pi Weekly

Code a stepper motor

- [Presenter] Last week we connected a stepper motor to a Raspberry Pi. We used a motor driver, the L293D to handle the current that's too large for the Raspberry Pi. This week let's spend some time with the code controlling the hardware. Hi, I'm Mark Niemann-Ross and welcome to this week's edition of Raspberry Pi Weekly. Every week we explore the Raspberry Pi and share useful tips. Let's start with the project we built last week. This connects a stepper motor to the Raspberry Pi. The code to control this is found in the exercise files. Chapter two. Zero two, zero eight step motor dot Pi. On the Raspberry Pi, you can use the Thorny application to open up code. Lines one through 13 set up definitions we'll need later in the code. Lines 16 and 17 set up four GPIO pins to be outputs. Lines 20 and 21 enable the L293D chip so it can turn on the motor controller circuits. Lines 25 through 27 sets up logic that will control the motors. Look at line 26, turn clockwise is defined as a list of tuples. Zero comma one comma zero comma zero. Then zero comma one comma zero comma one, et cetera. Each tuple contains a combination of ones and zeros. The ones and zeros represent the on/off state of the four enabled pins on the L293D motor controller. Each tuple represents a step in the sequence to turn the stepper motor. Run the sequence one way, the motor turns forward. Run the sequence backwards, and the motor turns backwards. And that's exactly what the function defined in line 29 does. The turn the motor function controls the number of steps which controls how far the motor turns. It also controls the delay between steps which controls how fast the motor turns, and it controls the clockwise or counterclockwise direction of the motor. Line 35 places a value in delay variable which will control the speed of the rotation. Line 36 defines the number of steps of rotation. This controls how far around the motor turns. Finally, in line 38 a while loop starts that sends a command to turn clockwise then counterclockwise and then repeat ten times. I encourage you to experiment with this code, in particular lines 26, 35 and 36. Or can you read a value from an input and then reflect that value in the direction and speed of the stepper motor. For example, try creating an analog clock by reading the time and then moving the motor to point to the current hour. Thanks for joining me for this episode of Raspberry Pi Weekly. Be sure to join the LinkedIn group and check out previous episodes on LinkedIn Learning. I'll see you next week with more Raspberry Pi adventures.

Contents