Thursday, June 6, 2013

Arduino: Write a stepper motor library

Arduino has a Stepper library within the distribution, which can be used to drive most stepper motors. However, by writing a driving library by self, one can more clearly understand how stepper motor works.

I use a 28BYJ-48 Stepper motor, together with a ULN2003 chip. ULN2003 is a high-voltage transistor array, which can be used to convert 5v input from Arduino to 50v output, which is sufficient to drive the stepper motor.

Here's a datasheet for 28BYJ-48. It is very easy to drive the motor: just send the signals in sequence, will the motor rotate clockwise. If reversing the signal sequence, the motor will rotate counter-clockwise.

Here's a sample program that drives the motor continuously. It uses pin 8,9,10,11 to drive the four input of 28BYJ-48.

int interval = 1;

void setup() {
 pinMode(8, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(10, OUTPUT); 
 pinMode(11, OUTPUT);
}

void loop() {
  // step 1
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  delay(interval);  
  // step 2
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  delay(interval);
  // step 3
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  delay(interval);
  // step 4
  digitalWrite(8, LOW);
  digitalWrite(9, HIGH);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  delay(interval);
  // step 5
  digitalWrite(8, LOW);
  digitalWrite(9, HIGH);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  delay(interval);
  // step 6
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  delay(interval);
  // step 7
  digitalWrite(8, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  delay(interval);
  // step 8
  digitalWrite(8, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  delay(interval);
}


We will now discuss how to control the rotation speed and angle. From the datasheet it is known that the step angle for this motor is 5.625° / 64, which means it will take 64 steps for the motor to turn a round and each step is 5.625°.

By changing the interval after each steps, the rotation speed can be adjusted. However, for a stepper motor the rotation speed is not what we care most. We care more about the rotation angle, which can be  adjusted by the step count. Thus we could do it by simply adding such a for loop to control the steps it goes. For this motor 64 steps make a round and half a round is 32 steps.

void loop() {
   for(int i = 0 ; i < steps ; i++) {
      step(); 
   }
}

Now it should be clear how a stepper motor works. Wrap them all together and you can write your own stepper motor library. Good luck!

No comments:

Post a Comment