最近周口一大学生在自家菜园里做的铁路模型火了,刚好在浏览外网的时候发现了国外一网友的项目,感觉非常有意思。这位网友使用Arduino单片机实现自动配线模拟铁路布局,作为程序员或者电子爱好者可以参考学习一下。
文末附项目源码。首先我们看下这位网友的演示视频。
实验所需材料:
- 1×Arduino微控制器几乎所有的都会起作用。
- 1×L298N双H桥电机驱动器
- 6×公母跳线
- 7×公母跳线
- 1ד禁闭”轨道
将下述源码烧录到Arduino开发板中。
- 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.
- void check_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.
- }
- }
- }
- void switch_to_pass(){
- digitalWrite(11,LOW);
- digitalWrite(12,HIGH);
- delay(200);
- digitalWrite(12,LOW);
- }
- void switch_to_main(){
- digitalWrite(12,LOW);
- digitalWrite(11,HIGH);
- digitalWrite(11,HIGH);
- delay(200);
- digitalWrite(11,LOW);
- }
- void setup() {
- pinMode(A0,INPUT);
- pinMode(9,OUTPUT);
- pinMode(10,OUTPUT);
- pinMode(11,OUTPUT);
- pinMode(12,OUTPUT);
- }
- void loop() {
- 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.
- }
感兴趣的朋友可以试试哦~~