Introduction: Simple Light Break Detection
What happens in this circuit is that light from the led shines on the photocell. When that light is interrupted, the resistance of the photocell changes and the transistor is turned on, turning the relay on.
A contact from this relay causes an LED to illuminate.
I know how difficult it can be to figure out which lead is which when comparing a "real device" to a schematic, so I am showing the transistor and LED here.
There is a diode (looks backwards) by the relay coil.
Why does it need to be there?
The simple answer is: to protect the transistor from overvoltage.
The longer answer: Voltage (across a coil) equals L (inductance of the coil) multiplied by dI/dt (change in current divided by change in time). For argument's sake, you can almost ignore the inductance and the current--turning off the relay happens very rapidly (dT), the time to switch off, is very small; maybe a few millionths of a second. If the number in the denominator (change in time) is almost zero, the total answer will move toward infinity.
Physical constraints won't let it get too crazy, but a spike big enough to blow out electronics is quite likely. The diode allows the current to flow backward through the coil, preventing damaging voltage.
I put together a simple system with a prototype board to show how you can detect the movement of a model train, car or passing object.