/* Stepper Motor Control by Tom Igoe This program moves a stepper motor 100 steps in one direction, then 100 steps in the opposite direction, indefinitely. Created 21 October 2005 Updated */ int motorStep[4]; // array to hold the stepping sequence int thisStep = 0; // which step of the sequence we're on // function prototypes: void stepMotor(int whatStep, int speed); void blink(int howManyTimes); void setup() { /* save values for the 4 possible states of the stepper motor leads in a 4-byte array. the stepMotor method will step through these four states to move the motor. This is a way to set the value on four pins at once. The digital pins 8 through 13 are represented in memory as a byte called PORTB. We will set PORTB to each of the values of the array in order to set digital pins 8, 9, 10, and 12 at once with each step. We're representing the numbers as hexadecimal values below, but it'd be nicer to represent them as binary numbers, so that the representation shows us visually which pins of PORTB we're affecting. */ motorStep[0] = 0x0A; // in binary: 0000_1010; motorStep[1] = 0x06; // in binary: 0000_0110; motorStep[2] = 0x05; // in binary: 0000_0101; motorStep[3] = 0x09; // in binary: 0000_1001; /* The DDRB register is the Data Direction Register. It sets whether the pins of PORTB are inputs or outputs. a 1 in a given position makes that pin an output. A 0 makes it an input. */ // set the last 4 pins of port b to output: DDRB = 0x0F; //0b0000_1111; // set all the pins of port b low: PORTB = 0; //0b0000_0000; // start program with a half-second delay: delay(500); // blink the reset LED 3 times: blink(3); } void loop() { int i = 0; // a counter /* move motor forward 100 steps. note: by doing a modulo operation on i (i % 4), we can let i go as high as we want, and thisStep will equal 0,1,2,3,0,1,2,3, etc. until the end of the for-next loop. */ for (i = 1; i<= 100; i++) { thisStep = i % 4; stepMotor(thisStep, 10); } // move motor backward for (i = 100; i >=1; i--) { thisStep = i % 4; stepMotor(thisStep, 10); } } //Step the motor forward one step: void stepMotor(int whatStep, int speed) { // sets the value of the eight pins of port c to whatStep PORTB = motorStep[whatStep]; // vary this delay as needed to make your stepper step: delay(speed); } // Blink the reset LED: void blink(int howManyTimes) { int i; for (i=0; i< howManyTimes; i++) { digitalWrite(13, HIGH); delay(200); digitalWrite(13, LOW); delay(200); } }