Okay - Now I've done it :D...
Got looking for Direct Port I/O and found a part of the Arduino documentation that doesn't seem to have a direct link.
Here's the link - Arduino Reference - Arduino Reference
It explains some of the problems and some of the uses. In a general Arduino project you might not want to use this approach as there are a few pitfalls that the Arduino IDE hides from you, and that is not always a bad thing. As i intend to use this in a dedicated chip it should cause me no problems.
Port B on the Arduino/ATMege328 is pins 8, 9, 10, 11, 12, 13, with the 2 remaining pins used by the crystal/resonator
DDRB is the Data Direction Register. Assigning 1 to a bit makes it an output, 0 makes it an input.
PORTB is the predefined variable that lets you read or write port B.
PORTB = B0001 turns on pin 8 and turns off pin 9, 10 & 11.
I also used pre-initialized arrays to set up the step patterns.
Down to 1232 bytes.
Here's the last version of the code -
/*
Step & Direction Stepper Driver
Pins 8, 9, 10, 11 are tied to transistors
for each of the motor phases.
Pins 2 & 3 are used as interrupts,
Pin 2 as Step and 3 as Direction.
*/
// the following 3 arrays contain the bit patterns to drive the transistors to in turn drive each of the phases of the stepper
int patSimple[] = {B0011,B0010, B0100, B1000, B0001, B0010, B0100, B1000};
int patWave[] = {B0011, B0110, B1100, B1001, B0011, B0110, B1100, B1001};
int patHalf[] = {B0001, B0011, B0010, B0110, B0100, B1100, B1000, B1001};
int pinDir = 3;
volatile int ctr;
volatile int dir;
void setup()
{
DDRB = B1111 ; // this enables Port B Bits 0 - 3, Arduino I/O 8, 9, 10, 11 as outputs
pinMode(pinDir, INPUT);
ctr=0;
dir = 0;
attachInterrupt(0, Step, RISING); // Depending on the application FALLING might be a better choice.
attachInterrupt(1, Direction, CHANGE);
}
void loop()
{
// Nothing to see here...
}
void Step()
{
if (dir)
{
ctr-- ;
}
else
{
ctr++ ;
}
ctr = ctr & 7;
// 2 of the following 3 lines must be commented.
// PORTB = patsimple[ctr]; // Simple Stepping
// PORTB = patWave[ctr]; // Wave Stepping
PORTB = patHalf[ctr]; // Half Stepping
}
void Direction()
{
dir = -digitalRead(pinDir); // Direction is 0 (zero) or -1 (minus one)
}