Using DTR (data terminal ready) and RTS (request to send) pins of a PC serial port (RS-232) without actually using the serial data pins, we can interface at least two relay devices with a computer. Windmeadow Labs has an excellent article on how to achieve this using a bipolar transistor (BJT). Here I will show you a similar relay control circuit built using an opto-isolator and a MOSFET.

Here is the circuit diagram:

An Isolated MOSFET Serial Port Relay Controller

The benefit of using an opto-isolator is that the rest of the controller circuit is totally isolated from the serial port and thus prevents the port from accidentally being damaged by wrong wiring or current surge due to a failed component. And by replacing the drive circuitry from using a BJT to a MOSFET, the switching capability is improved dramatically, making switching higher current load more reliable and more efficient.

Here is a picture of the finished board:

Circuit Board
Circuit Board

And here is a simple program that toggles the relay on and off at an interval of 0.5 second.

#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdlib.h>

#define _SERIAL_PORT "/dev/ttyS0"

int main(int argc, char **argv)
{
        int fd, status = 0, cmd = 0;

        if ((fd = open(_SERIAL_PORT, O_RDWR | O_NDELAY)) < 0)  exit(1);

        while(1) {
                if (cmd) cmd = 0;  else cmd = TIOCM_DTR;

                ioctl(fd, TIOCMSET, &cmd);
                ioctl(fd, TIOCMGET, &status);

                if (status & TIOCM_DTR) puts("ON"); else puts("OFF");
                usleep(500000l);
        }

        close(fd);
}
Be Sociable, Share!