How do automatic rail crossings work?

I cannot understand how the automatic crossings at railroads work, where the barriers come down to stop vehicles.
What tells the barriers to come down? How do they know when to go back up? A train can come from either direction so can the equipment work for either direction?

It is quite trivial to have sensors which would lower the barrier when there is a train entering any section of track. Detecting floppitrons is still quite difficult but detecting trains has been done for decades with ease.

I’m afraid I don’t know the precise mechanics of the sensors, but you’ll find them up both ways from a crossing. In the one case I researched once, there was a speed sensor way up the track that was used to predict the approximate arrival time of the train, and thus have the lights going by then already, plus a sensor closer to the gates, in case the train sped up in the mean time.