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:
Become the Maker you were born to be. Try Arduino Academy for FREE!
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;
}
}
Become the Maker you were born to be. Try Arduino Academy for FREE!
Can the IR Obstacle Avoidance Sensor Modules be used for this? I have several laying around…
It seems the code only works if Sensor1 is tripped first.. it does not work bi-directional?
Not yet.
i am very new to arduino and trains, im running n scale.i copied your code and got an error code saying…exit status 1;and redefination of 'void setup()'. could you help me with this ? thanks
email me your sketch at greentrust@gmail.com
That’s very nice of you Steve. I hope you both got it sorted.
Looks like a great tool for my model railway. When I downloaded the sketch I got error comment Stray 342. I just retyped the lines and deleted the old ones. I tested it and am now waiting on some parts to build it.
Thanks for the information. You are very kind.
Cheers,
Richard.