Model Railroad speedometer, bidirectional sensing issue

I built a scale speedometer for our club layout. When the train trips the first IR sensor, it starts a timer, when it trips the second, it tops the timer, calculates and displays the scale speed, and resets after a delay (to give the train time to pass). Primarily the trains move in the same direction, but on occasion they reverse direction, so sensor 1 will have to be sensor 2, and sensor 2 will have to be sensor 1. I need to be able to detect which sensor trips first, reassign the sensor names, while starting the timer. Any ideas?

Project is at Arduino Your Home & Environment: Arduino Model Railroad Scale Speedometer - Finished

#include  "Wire.h"
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_7segment matrix = Adafruit_7segment();

//user variables
float distance = 24; //inches between sensors
int scale=87;

int sensor1 = 4;
int sensor2 = 5;
bool s1Covered;
bool s2Covered;
float start, finish, elapsed, miles, hours, mph, scaleMPH;

int started=0, finished=0;
int scale=87;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
  matrix.begin(0x70);

}

void loop() {
  // put your main code here, to run repeatedly:
  //Serial.println("Ready ....");
  matrix.print(0.0);
  matrix.writeDisplay();
    //finished=0;
    s1Covered=digitalRead(sensor1);
    if (s1Covered==0 && started==0){
      start=millis();
      started=1;
      Serial.println("Started");
    
    }
    s2Covered=digitalRead(sensor2);

    if (s2Covered==0 && started==1){
      finish=millis();
      finished=1;
      Serial.println("Finished");
    
  elapsed = finish-start; // millis

  elapsed = elapsed /1000; // seconds
  Serial.print("Seconds: ");
  Serial.println(elapsed);
  miles = distance / 63360; // miles
  hours = elapsed / 3600; // hours
  mph = miles / hours;
  scaleMPH = mph * scale;
  Serial.print("Scale MPH: ");
  Serial.println(scaleMPH);
  
  // print a floating point
  matrix.print(scaleMPH);
  matrix.writeDisplay();
  delay(5000);

  started=0;
  finished=0;
    }
  }

MRRspeedometer.ino (1.46 KB)

When the train trips the first IR sensor, it starts a timer

For some definition of first. If the sensors can be tripped in any order, there is no such thing as the first sensor or the second sensor.

There is a sensor and a time that it was triggered. There is another sensor and another time that it was triggered.

The delta time between the triggers will be positive if one sensor it triggered first, or negative if the other sensor is triggered first. The sign tells you the direction the train was going. The absolute value tells you the speed.

Excellent!