8.4 Programming the Stepper Motor
In order to get the stepper motor to work the way we
want it to, we need to import a library that makes it easy to
incrementally rotate the motor’s shaft in either direction at the
speed we want it to move. Fortunately, controlling a stepper motor
is easy thanks to Adafruit’s AFMotor
motor shield library.[83] As you do with most Arduino
libraries, extract the downloaded zip file, rename the extracted
folder (AFMotor
), and place it in
the Arduino libraries folder. For more details, refer to Appendix
1, Installing
Arduino Libraries.
With the AFMotor
library installed, launch the Arduino IDE. Let’s write a sketch
that will test the stepper motor. The code will do the
following:
-
Load the
AFMotor
library. -
Create an AFMotor stepper motor object and set the stepper’s connection and steps per revolution (i.e., how fast the stepper motor’s shaft rotates).
-
Move the shaft clockwise and counterclockwise using the stepper motor’s two coils. By the way, this action is known as double-coil activation, and it produces greater torque compared to using just a single coil at a time. We will need that extra torque to move the curtain string.
Here’s what the completed sketch should look like:
CurtainAutomation/StepperTest.pde | |
#include
<AFMotor.h> |
|
|
|
AF_Stepper motor(48, 2); |
|
|
|
void
setup() { |
|
Serial.begin(9600); |
|
Serial.println("Starting stepper motor
test..."); |
|
// Use setSpeed to alter speed of
rotation |
|
motor.setSpeed(20); |
|
} |
|
|
|
void
loop() { |
|
// step() function |
|
motor.step(100, FORWARD, DOUBLE); |
|
motor.step(100, BACKWARD, DOUBLE); |
|
|
|
} |
Note that this test code is essentially a subset of the sample code available from Ladyada’s motor shield web page.[84]
Save and upload the sketch to the Arduino. If all goes well, your stepper motor should spin clockwise and counterclockwise until you remove power or upload a new sketch. If the shaft isn’t moving, make sure your stepper motor wiring is properly connected. Also make sure that you are using a 12-volt power supply connected to the Arduino, since the motor needs that amount of voltage to move. If you’re having a hard time seeing which direction the shaft is rotating, affix a small piece of folded tape on the shaft. It should be easier to see the tape flag move back and forth as the shaft moves.
Now that your hardware is working, it’s time to add the temperature and light sensors to give the stepper motor a bit more relevance to its intended motion.