Sunday, November 6, 2016

Arduino Model Railroading - Scale Speedometer

The guys at the Model Railroad Club wanted a scale speedometer displaying the scale speed of the train as it passes a point on the layout. I'm using two IR transceivers connected to an arduino to detect the time it takes to pass between 2 points, and then displaying the scale speed.

Currently we are using the Serial Monitor, but Part 2 will be about the 3 seven segment display and I2C port expander used to drive them.



Wiring:
The circuit diagram is the same as the one we posted here, but just doubled.

Code:

int sensor1 = 4;
int sensor2 = 5;
bool s1Covered;
bool s2Covered;
float start, finish, elapsed, miles, hours, mph, scaleMPH;
float distance = 24; //inches between sensors
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);
}

void loop() {
  // put your main code here, to run repeatedly:

    //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);
  started=0;
  finished=0;
    }
  }




2 comments:

  1. It seems the code only works if Sensor1 is tripped first.. it does not work bi-directional?

    ReplyDelete