The following sketch uses the Serial Monitor, so once the sketch is installed and running, open the Serial Monitor and enter a number of 'steps'. Try a value of about 500, this should cause the motor to turn through about 360 degrees. Enter -500 and it will turn back in the reverse direction.
/* Adafruit Arduino - Lesson 16. Stepper */ #include <Stepper.h> int in1Pin = 12; int in2Pin = 11; int in3Pin = 10; int in4Pin = 9; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); // this line is for Leonardo's, it delays the serial interface // until the terminal window is opened while (!Serial); Serial.begin(9600); motor.setSpeed(20); } void loop() { if (Serial.available()) { int steps = Serial.parseInt(); motor.step(steps); } }
As you might expect, there is an Arduino library to support stepper motors. This makes the process of using a motor very easy.
After including the 'Stepper' library, the four control pins 'in1' to 'in4' are defined.
To tell the Arduino Stepper library which pins are connected to the motor controller, the following command is used:
Stepper motor(768, in1Pin, in2Pin, in3Pin, in4Pin);
The first parameter is the number of 'steps' that the motor will take to complete one revolution. The motor can be moved by one step at a time, for very fine positioning.
Serial communications is then started, so that the Arduino is ready to receive commands from the Serial Monitor.
Finally the following command sets the speed that we wish the stepper motor to move, when we subsequently tell it how many steps to rotate.
motor.setSpeed(10);
The 'loop' function is very simple. It waits for a command to come in from the Serial Monitor and converts the text of the number sent into an int using 'parseInt'. It then instructs the motor to turn that number of steps.
Text editor powered by tinymce.