Thanks for that. I have now got this working like so where the stepper is interrupted and the direction switched on the toggle of a switch.
What I want to ask is why when I restart serial monitor it always goes from the start of the count. If I start the serial monitor when i first uploaded the programme the count number starts at 0 and if I start the serial monitor after running for 1 minte it starts at 0, doesn't the programme just keep counting? I don't understand why the count is reset.
int motorPin1 = 9;
int motorPin2 = 10;
int motorPin3 = 11;
int motorPin4 = 12;
int interruptpin = 0; // Interrupt 0 is on DIGITAL PIN 2!
volatile int state = LOW; // The input state toggle
int delayTime = 3; // 3 msecs seems to be as fast you can go and not have it
//stick when you change direction
int count =0;
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
Serial.begin(9600);
//Attach the interrupt to the input pin and monitor for ANY Change
attachInterrupt(interruptpin, stateChange, CHANGE);
}
void loop() {
if (state){
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
count = count + 1;
Serial.println(count);
delay(1000);
}
else
if (!state) {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
count = count - 1;
Serial.println(count);
delay(1000);
}
}
void stateChange()
{
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// If interrupts come faster than 50ms, assume it's a bounce and ignore
if (interrupt_time - last_interrupt_time > 50)
{
state = !state;
}
last_interrupt_time = interrupt_time;
}