Model Railroad Controller

Make things

Using obniz, you can operate a model train from your smartphone or PC. Also, it makes it possible to stop automatically to the position specified only by the camera image without using anything of the sensor by using OpenCV.

Materials

How to make

Hardware connection

Connect Motor driver for model railroad and Point driver for model railroad to an obniz Board.

Please also refer to the following pages for more information about wiring (written in Japanese).

The railway model operation board we used includes the following functions.

  • power supply to obniz
  • receives signals representing the traveling direction and speed from obniz and supply signal to the rail
  • receives a selection signal for straight-curvilinear of the points from obniz and output signals to the points

Software

The program uses OpenCV.js for image processing. Moving objects are detected by acquiring the difference in the image in the processVideoMoving() function.

...
cap.read(src);
cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY);
if (first_flag) {
  gray.copyTo(before);
  first_flag = false;
}
cv.addWeighted(gray, 0.5, before, 0.5, 2.2, before);
cv.convertScaleAbs(before, b1, 1, 0);
cv.absdiff(gray, b1, mdframe);

let delay = 1000 / FPS - (Date.now() - begin);
setTimeout(processVideoMoving, delay);
...

The processVideoMoving() function is repeated. In the function, it loads camera images into the array at cap.read(src);, and convert image to grayscale at cv.cvtColor (src, gray, cv.COLOR_RGBA2GRAY);. Then, it blends the image of the previous loop and the image of the current loop at cv.addWeighted(gray, 0.5, before, 0.5, 2.2, before);, and detects the difference between them at cv.absdiff(gray, b1, mdframe);.

Program

(You can also see it at GitHub Gist)

How to use

UI on smartphone

Manual control by UI

The railway model can be controlled manually by operating the “マスコン台” or “簡易運転台”.

In “駆動設定”, you can set acceleration, motor drive sound, motor vehicle type, etc.

Automatic control by image processing (OpenCV)

The railway model can be stopped automatically at the position specified from the image of the camera by using OpenCV.

The camera image is displayed after tapping “カメラを起動” from the “カメラ制御” tab. If you specify an area by tapping two points in the image in order, motion detection will be performed within that area.

When motion is detected, it is detected that the train has passed and the brakes are applied. When stopped, acceleration will start again after a certain time.

Appendix