input as interrupt

hi all,

having a bit of an issue writing a code to use momentary-contact switch inputs to change between timed sequences.

i have a motor running two preset timed on/off sequences, one forward and one backwards. i have no trouble switching motor direction through the h bridge with two switches (they will act as limiters in the appliance’s lateral travel) if the motor is always on. when i introduce on/off timings though, the board clearly needs to go through the full sequence before reading switch input, which keeps the switches from really being able to act as limiters.

here is what i have so far. as you can see, this works fine if the input happens to be happening at the moment the code looks for it, but i need the input to interrupt the sequence at any time. I realize looking at it now that i have some redundancies left over from different iterations between the Val and Control ints…

int backpin = 2; // switch input 2
int forwardpin = 1; // switch input 1
int motor1Pin = 3; // H-bridge leg 1
int motor2Pin = 4; // H-bridge leg 2
int speedPin = 9; // H-bridge enable pin
int ledPin = 13; //LED
int control = 0; //count switches motor direction
int val = 0;

void setup() {

pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(speedPin, OUTPUT);
pinMode(ledPin, OUTPUT);

pinMode(backpin, INPUT);
pinMode(forwardpin, INPUT);

digitalWrite(speedPin, HIGH);

}

void loop()

{
if (control < 1)
{
digitalWrite(motor1Pin, LOW); // forward off
digitalWrite(motor2Pin, HIGH); //reverse on

delay(2000);
digitalWrite(motor2Pin, LOW);

delay(2000);
digitalWrite(motor2Pin, HIGH);

delay(2000);
digitalWrite(motor2Pin, LOW);

delay(2000);
digitalWrite(motor2Pin, HIGH);

val = digitalRead(backpin);
if (val == HIGH)
{
control = 2;
digitalWrite(motor2Pin, LOW);
}
}

if (control > 1)
{
digitalWrite(motor1Pin, HIGH); // forward on
digitalWrite(motor2Pin, LOW); //reverse off

delay(2000);
digitalWrite(motor1Pin, LOW);

delay(2000);
digitalWrite(motor1Pin, HIGH);

delay(2000);
digitalWrite(motor1Pin, LOW);

delay(2000);

digitalWrite(motor1Pin, HIGH);

val = digitalRead(forwardpin);
if (val == HIGH)
{
control = 0;
digitalWrite(motor1Pin, LOW);
}
}

}