Browse over 10,000 Electronics Projects

Controlling a relay and motor with a serial port

Controlling a relay and motor with a serial port

For a while I have wanted to control things with a serial port. It was pretty easy to control a relay with a serial port. With a standard serial port you can control 2 relays. (with a parallel port you can control 8 relays, but I don’t have a parallel port on my system).
A standard PC serial port has 9 pins. Pin 4 – DTR (data terminal ready) and Pin 7 – RTS (request to send) can be used to control a relay. These two ports don’t actually send data. They are used to signal the other device to tell it when to send data.

These pins can be set high or low. When set high, they each go to about +9 volts. When set low they go to about -9 volts. This voltage swing is what is used to run the the relay.

A serial port pin does not have enough current to drive a relay by itself. You must build a simple cicuit to drive the relay. You have the DTR pin drive a transistor, which in turn drives the relay. The parts needed are:


1. NPN transistor, Radio Shack part #276-1617
2. 2 diodes, Radio Shack part #276-1103
3. 4.7k resistor
4. reed relay, Radio Shack part #275-233
5. 9 volt battery

To drive the pin, I wrote a small C program. It loops and turns DTR high then low then repeats itself.

You have to run this program as root. To compile it, just download relay.c and do gcc relay -o relay.c

To run type ./relay /dev/ttyS0 (or whatever serial port you use)

This circuit worked well with my built in serial port. I was able to run a small dc motor. I also used a USB to Serial adapter and it worked too. If I had the relay switch on/off quickly (say on/off ten times in a row within 5 seconds) the USB serial port would lock up. I would have to unplug and plug it back in. I am guessing the motor is generating some interference that causes the usb serial port to lock up. I haven’t had any problem with my built in serial port though.

Visit Here for more.