Smart Modeltrain Protection System

by NieuborgJente in Circuits > Raspberry Pi

50 Views, 0 Favorites, 0 Comments

Smart Modeltrain Protection System

test.jpg

Welcome to the Smart Modeltrain Protection System (SMPS)! If you are a model railway enthusiast, you know that keeping your trains running smoothly without collisions is half the fun but doing it completely by hand can be a stressful job. Whether you want to step back and watch your miniature world run flawlessly on autopilot, or take full control from your laptop or smartphone, this project is for you.

In this Instructable, we are going to build an automated signaling and safety system using a Raspberry Pi. By combining Infrared, RFID, time of flight sensors hidden along the tracks with signals that stops your train, level crossings (servo), turnout mechanism that can be controlled from your phone.

Supplies

Materials:

  1. Raspberry pi 5
  2. Raspberry PI T-cobbler
  3. Servo motor
  4. Infrared break beam sensor
  5. Time of flight sensor
  6. RFID-reader
  7. RFID-sticker
  8. Breadboard Power Supply
  9. Relais
  10. Marklin 74491 - Electric Turnout Mechanism
  11. Marklin 74030 - Center Rail Insulators
  12. Leds (color: Green, orange, red)
  13. LCD 1602 module
  14. Connectors
  15. Button
  16. Wires
  17. Breadboard
  18. marklin external powersupply
Note: Marklin doesn't make external power supply anymore. You can use a old powersupply from marklin
Note: Wires from old cables can be used.
Note: A breadboard is optional. You can solder everything.


Tools:

  1. 3D printer
  2. Hot glue
  3. Existing Märklin C-Track layout
  4. Woodworking tools
  5. Soldering iron
  6. Solder tin
  7. Ethernet cable
  8. Pc
Note: You will need to have a Märklin track and the knowledge to use it. If you don't, follow this guide from Märklin.


Software:

  1. VNC viewer
  2. Visual studio code
  3. SQL workbench


Code repository

  1. Github

3D Printing

IMG_5246.jpg

Now, we are going to print the required 3D-printed pieces. You can find all the models via the links provided below. We will start with the two support pieces for the servo. Once that is done, we will print the signal housing to hold the LEDs. You need to print this piece twice. You will also need to print the barrier arms for the servo, as well as two RFID cases and two poles.


Files:

The servo support is design by Mauro Eclis via Makerworld (CC BY-NC-ND).

The signal housing is design by perk via printables (CC BY-NC-SA).

The barrier arm for the servo was designed by me via Makerworld (CC BY).

The RFID case is design by The ThingiLab via Makerworld (CC BY-NC-SA).

The pole is design by dr_juan via Thingiverse (CC BY-SA).

Setup Raspberry Pi

ethernet.jpg
terminal.png

1. Preparing the SD Card

While the 3D printer is printing, we will start setting up the Raspberry Pi. First, you need to write an image file to the SD card. To do that, you can follow this guide. You can download the image from this drive. This image contains everything you need for a smooth start (including a MariaDB server, Apache server, libraries, and more).


2. connecting to pi

Once that is done, place the SD card into the Pi and connect the power supply. The Pi will now start setting things up. To connect to the Pi, you will need to set a static IP address on your PC's ethernet port. If you don't know how, you can follow this guide. You only need to fill in the IP address and subnet mask (see picture). The IP address to enter on your PC is 192.168.168.10 and the subnet mask is 255.255.255.0.


3. Connecting via VS Code and SSH

When that is done, connect the ethernet cable between the Pi and your PC. Now, we will install Visual Studio Code (vscode). Once that is finished, you can connect to the Pi via SSH in VS Code. If you don't know how to do that, you can use this guide. The username is student with the password P@ssw0rd. The hostname is 192.168.168.169. When you are connected to the Pi, it will ask for a new password. You can choose this password yourself.


4. Configuration of the Pi

Open a new terminal in VS Code (see picture / click the button in the top left of VS Code) and enter sudo raspi-config. This will open a blue screen in the terminal, where you can only navigate using the arrow keys on your keyboard.

Navigate to System Options and press enter. Then, choose Boot / Auto Login and press enter. From here, select Desktop Autologin and press enter. If you are prompted to reboot, select No (do not reboot yet).

You will now be back in the main menu of raspi-config. Navigate to Interfacing Options and press enter. Once there, you will need to activate both I²C and SPI.

After activating those, navigate to Finish. Now, type sudo reboot in the terminal. The Pi will reboot. Once it is back online, reconnect to the Pi.


5. Wifi

Note: I use the VNC Viewer by RealVNC, but you can use any VNC viewer you want.

Install a VNC Viewer. Once the VNC Viewer is installed, connect to the Pi via VNC by following this guide.

Once you are connected to the Pi via VNC Viewer, you can follow this guide to set up Wi-Fi on the Pi so it can download updates and access the internet. After that is done, you are finished setting up your Pi!

Connecting Sensors

Schermafbeelding 2026-06-17 205332.png
IMG_5181.jpg

You made it through the setup steps! Now the fun starts: we are going to connect everything together. You can choose to solder everything or put it on a breadboard. I chose a combination, making it partly on a breadboard and partly soldered.


You can follow the breadboard and electrical diagrams to connect everything. If you don't know how to solder sensors or wires, follow this guide. If you don't know how to read an electrical diagram, follow this guide.

Note: Orange wire is 3v3, Red wire is 5v, Black wire is ground


1. Sensors

Infrared break-beam sensors: An infrared break-beam sensor uses infrared light to detect if the beam of light is being interrupted. In this project, I use it to detect when a train passes the signal.


RFID sensors: An RFID sensor is a device that can read from or write to cards (like a credit card). I use it to identify which specific train passes the sensor, which is possible because each train has an RFID sticker attached to it.


Time-of-Flight sensor (ToF): A ToF sensor measures distance using a laser. I use it to measure the speed of a train. You can calculate speed using the formula:

speed = (distance_1 - distance_2)/time_between_measurements


2. Actuators

LEDs: I use LEDs to create signals that follow the Belgian railway system guidelines.


Servo: The servo functions as the barrier for a level crossing.


Turnout mechanism: I use a turnout mechanism to switch the turnouts (switches) in the track.


3. Display

LCD 1602: The LCD display shows whether the system is in manual or automatic control, as well as the IP address you need to navigate to the website.

Making the Signals

IMG_5191.jpg
IMG_5195.jpg
IMG_5193.jpg
IMG_5192.jpg

Now it's time to assemble the 3D-printed signal and get the electronics ready. Follow the steps below carefully to ensure everything is wired correctly.


1. Assemble the 3D print

Gather your 3D-printed signal parts.Use hot glue to assemble the pieces together, following the original creator's instructions.


2. Position the LEDs

Place 1 green, 2 orange, and 1 red LED into their correct positions inside the signal housing by following this guide.


3. Soldering the resistors (Ground Side)

Take a 1000 ohm resistor and solder it to the Ground (GND/cathode) leg of each LED. Solder a wire that is long enough to reach your breadboard to the other end of each resistor.


4. Soldering the power (3V3 Side)

Connect the 3V3 (anode) pins of all the LEDs together. Solder a wire that is long enough to reach your external power supply to this combined 3V3 line.


5. Secure everything

Once all your soldering is complete and tested, use a bit of hot glue around the LEDs to secure them firmly in place inside the housing.


6. Other prints

You can assemble the other 3D prints using hot glue, following the guide on the designer's page.

Modifying Model Train

IMG_5248.jpg
IMG_5247.jpg

Now, place the RFID sticker on top of the train, as shown in the picture. If the roof of the train is curved, you can use a piece of cardboard and some hot glue to mount the RFID sticker flat.

Modifying Tracks

IMG_5250.jpg
IMG_5249.jpg

Now we are going to solder the cables to the track, as shown in the picture, so that the signals can stop the model train. To connect everything to the Märklin external power supply, use the included connectors.

Connecting Github

vscode-3.png
vscode-2.png
vscode-1.png

Open VS Code and connect to the Pi via SSH. In the top-left corner, click on File and then select Open Folder.... Now, select the folder you want to use. I used a folder named project.

Once that is done, click on the top icon in the left sidebar (the Source Control or Explorer icon). You should see a menu open with a button labeled Clone Repository. Click it. A text bar will appear at the top where you need to enter this link and press enter.

Note: If you have problems with Git, you can follow this guide.


You should now see that the Pi is cloning the files. Once it is finished, a prompt will appear asking if you want to open the cloned repository. Click Open.

Testing Circuit

vscode-4.png

hier komt een foto van vscode met aanduiding van de kill terminal knop


I²C test

Now that we have everything connected and the code is ready, we are going to test it. Connect the Pi to the circuit using the T-Cobbler. Open a new terminal in VS Code and enter the following command: i2cdetect -y 1.

You should now see a table showing some numbers, one of which should be 29. If you do not see this, check whether everything is connected correctly on the circuit and ensure that I²C is turned on in raspi-config.


Creating venv

Now we are going to create a virtual environment (venv). A venv is an isolated folder within your project where you can install libraries, ensuring that your system's global Python installation doesn't get cluttered.

Enter the following command in the terminal and press enter: python3 -m venv venv_smps

Next, you need to kill the terminal (see picture / click the trash can icon in the terminal panel). Now, open a new terminal. You should see that a command is automatically run for you. This command activates the venv, and you should notice (venv_smps) appearing at the beginning of your terminal line.

Finally, type pip install -r req in the terminal, press the Tab key to autocomplete the filename, and press enter. The venv will now install every required library you need.


Testing

Open the test folder. You should be able to run every script (or piece of code) you find in there to check if your circuit works. If it doesn't, double-check your circuit connections.

Importing Database

sql-1.png

hier komt een foto van sql workbench met aanduiding naar de knop voor het maken van nieuwe connectie.


First, you need to install MySQL Workbench on your PC. Once it is installed, you should see the "Welcome to MySQL Workbench" screen. Here, click on the plus (+) icon.

Next, configure the connection to connect to the Pi via SSH by following this guide. The username for the database is root, and the password is S3crET.

Once you are connected, you can open and run the database code (see folder database) from the files you cloned earlier within MySQL Workbench. You now have a working database.

Connecting Database

In vscode you now copy the config_example.py and rename it to config.py. Now fill in config.py with your database credentials.

Configuring Web Interface

To verify your server is running, navigate to http://192.168.168.169 on your PC. You should see the Apache2 Debian Default Page, which is currently served from /var/www/html/ on your Raspberry Pi. Since we want to use the front-end folder from your cloned repository instead, we need to update the Apache configuration. Ensure you have root privileges by running sudo -i if you aren't root already, then open the default site configuration file with the command: nano /etc/apache2/sites-available/000-default.conf.

Scroll down using the arrow keys until you find the DocumentRoot line. Change this path to point to your repository: DocumentRoot /home/student/project/<name_of_your_repo>/front. Save and exit the file by pressing Ctrl + X, followed by Y and Enter. To apply this change, restart the web server using service apache2 restart.

Next, we need to adjust the global directory permissions so Apache is allowed to access your project files. Open the main configuration file by running nano /etc/apache2/apache2.conf and locate the <Directory /> block. Change the default configuration so it looks exactly like this:

<Directory />
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>

Save and exit this file (Ctrl + X, then Y and Enter). Now, set the correct ownership and permissions on your front-end folder so the web server can read it by executing the following two commands:

  1. sudo chown student:www-data /home/student/project/<name_of_your_repo>/front
  2. sudo chmod 0750 /home/student/project/<name_of_your_repo>/front

Finally, restart Apache one last time with service apache2 restart. You can verify if everything is running perfectly by checking the status with service apache2 status. Your output should show that the service is active (running).

Testing Backend

Now we are going to test the backend and the website. Open app.py in the backend folder and click Run. You should now see app.py running in the terminal.

If you encounter an error, search for it on Google; most of the time, the error message will tell you exactly what the problem is.

Next, open your favorite browser on your PC and navigate to https://192.168.168.169. You should now see a fully functional website where you can test everything. In the next step, I will explain what each page does.

Website

IMG_5266.png
IMG_5265.png
IMG_5264.png
IMG_5262.png

hier komt een foto van mijn website pagina track control

hier komt een foto van mijn website pagina train stats

hier komt een foto van mijn website pagina history

hier komt een foto van mijn website pagina settings


Track control

When you launch the website, you will find yourself on the Track Control page. Here, you can control the actuators by clicking on an icon and changing its status in the dropdown menu. You can choose to set everything to manual mode (manual control) or automatic mode, where the train operates entirely on its own.


Train Stats

Here you can see the stats of your model train, such as speed and rotations.


History

Here you can see the history of the actuator actions. By clicking on the icons, you can filter by actuator.


Settings

Here you can find the power-off button, as well as a debugger page.

Case

IMG_5204.jpg
IMG_5203.jpg
IMG_5202.jpg
IMG_5201.jpg
IMG_5200.jpg

Now we are going to build the enclosure to house the Raspberry Pi, breadboards, LCD, Märklin external power supply, relays, and other components.


I used a wooden wine box with the dimensions 25.9 cm x 33.5 cm. Alternatively, you can choose to mount everything under your table to keep the wires neatly tucked away.


You can use my sketch to see where you need to drill or cut the holes. I added a lid to the top of the enclosure, attached with a hinge. Once everything is finished, you can paint it however you like.

Mounting Case

IMG_5251.jpg
IMG_5253.jpg
IMG_5252.jpg

Now it is time to mount everything inside the enclosure. Use hot glue to secure all components that need to be fixed in place, such as the LCD and relays (see list down below). I used popsicle sticks to hold the Raspberry Pi and the power supply firmly in place. You can refer to the sketch and pictures to see exactly how to mount everything.


List components case

  1. Relais
  2. Marklin external power-supply
  3. raspberry pi
  4. breadbords
  5. lcd

Final Configuration

Create a new file named smps.service and add the following configuration:

[Unit]
Description=ProjectOne Project
After=network.target

[Service]
ExecStart=/home/student/project/<repo>/<venv>/bin/python -u /home/student/project/<repo>/backend/app.py
WorkingDirectory=/home/student/project/<repo>/backend
StandardOutput=inherit
StandardError=inherit
Restart=always
User=student
CPUSchedulingPolicy=rr
CPUSchedulingPriority=99

[Install]
WantedBy=multi-user.target

Next, copy this file to the system directory as a root user using the following command sudo cp smps.service /etc/systemd/system/smps.service.

You can now test the service by starting it: sudo systemctl start smps.service.

To stop the service, run: sudo systemctl stop smps.service.

If everything works as expected, you can enable the script to start automatically at boot: sudo systemctl enable smps.service.

To check the status of your service, use: sudo service smps status.

Time to Play

IMG_5238.jpg
IMG_5236.jpg
IMG_5237.jpg

Now that we have finished the construction, we can finally start playing!


Remember, this project is just the starting point. You can always make adjustments to the code and the infrastructure to add new features and make it even more fun.


Thank you so much for following my Instructables. I hope you enjoyed making it as much as I did. If you built your own, please click the "I Made It!" button below and share a picture or video—I would love to see your version!


Happy making!