Let's complicate our scheme. Now we divide the line into two sections. At the entrance of the each section we'll put the signal and let's go the train in a circle. There is one problem: if the train stops right above the sensor, then our previous sketch will get chaos.
The problem can be solved in many ways, but the most obvious and simple (at the same time get rid of “delay (200);” in the sketch) to put two sensors, instead of one. These modules are very cheap.
Let's change the previous scheme (see part 1). In the sketch on this part the latch code is given.