Making model train layouts is a great hobby, automating it will make it a lot better! Let us take a look at some of the advantages of its automation:
=>Low-cost operation: The whole layout is controlled by an Arduino microcontroller, using an L298N motor driver, their cost is almost nothing as compared to traditional train control throttles and power packs.
=>Ideal to put up at a display: Since no human interference is required to keep control of the layout, you can use it at a display where you cannot be always present to control the train and the turnouts.
=>Great for microcontroller hobbyists: If you are or want to start with Arduino and programming, this is a great project for you to practice your skills.
int i=0; //Integer to store the locomotive's speed at a scale from 0 to 255.int switchLimit = 80;// Integer to store the speed limit at which the train will enter the siding.voidcheck_n_switch(){
if(digitalRead(A0)==HIGH){//Checking if the sensor detects the train passing the sensored track.if(i<=switchLimit){//If the speed value is greater than the set value.
switch_to_pass();//Direct the train to the siding.
}
if(i>switchLimit){//If the speed value is less than the set value.
switch_to_main();//Direct the train to the mainline.
}
}
}
voidswitch_to_pass(){
digitalWrite(11,LOW);
digitalWrite(12,HIGH);
delay(200);
digitalWrite(12,LOW);
}
voidswitch_to_main(){
digitalWrite(12,LOW);
digitalWrite(11,HIGH);
digitalWrite(11,HIGH);
delay(200);
digitalWrite(11,LOW);
}
voidsetup() {
pinMode(A0,INPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
voidloop() {
switch_to_pass();//Switching turnouts to the siding since the train will start the journey fro there.for(i=0;i<=40;i++){//Increasing the speed of the locmotive to 40, at this speed the lights turn on but the train remains at rest.
analogWrite(9,i);
delay(10);
}
delay(1000);
for(i=40;i<=90;i++){//Increasing the speed of the locomotive to 90
analogWrite(9,i);
check_n_switch();
delay(500);
}
delay(4000);
for(i=90;i<=180;i++){//Increasing the speed of the locomotive to 180.
analogWrite(9,i);
check_n_switch();
delay(250);
}
delay(5000);
for(i=200;i!=90;i--){//Decreasing the speed of the locmotive back to 90.
analogWrite(9,i);
check_n_switch();
delay(500);
}
delay(5000);
while(digitalRead(A0)==LOW){//Wait for the train to cross the sensored track.
}
switch_to_pass();//Switch the turnouts to direct the train to the siding.
delay(10000);//Wait for the train to enter the siding.for(i=90;i!=50;i--){//Reduce the speed of the train gradually, bringing it to a halt.
analogWrite(9,i);
delay(500);
}
delay(2000);
for(i=50;i!=0;i--){
analogWrite(9,i);
delay(62);
}
delay(5000);//Wait for 5 seconds before repeating the whole process again.
}