[EN] Drive a relay with an USB-to-UART interface

Versione italiana sul sito dell’associazione LILIS.

The RS232 standard implements an hardware flow control mechanism. While TxD and RxD pins are used to send and receive data, DCD, DTR, DSR, RTS, CTS and RI allow devices which support hardware control flow to maintain a reliable data connection between a transmitter and a receiver.

Signal Pin  Pin  Direction  Full
Name   (25) (9)  (computer) Name
-----  ---  ---  ---------  -----
FG      1    -      -       Frame Ground
TxD     2    3      out     Transmit Data
RxD     3    2      in      Receive  Data
RTS     4    7      out     Request To Send
CTS     5    8      in      Clear To Send
DSR     6    6      in      Data Set Ready
GND     7    5      -       Signal Ground
DCD     8    1      in      Data Carrier Detect
DTR    20    4      out     Data Terminal Ready
RI     22    9      in      Ring Indicator

From the computer side the output pins are: RTS, DTR and obviously TxD.

Both RTS and DTR pins are usable to our scope, I have chosen the RTS one.

The RS-232 standard defines the voltage levels that correspond to the logical “one” in the range of +3V to +15V and the logical “zero” in the range of -15V and -3V but, through a TTL/CMOS converter, we can use 0V and +3.3V/+5V.
If you want to use a real RS232 port (DB9 connector) you can use the MAX232 IC to use a TTL or CMOS voltage level.

In a modern computer without a RS232 port you can use a cheap USB/TTL-232 interface like this, which already has the TTL voltage values.

Not all of these interfaces have all control flow pins so, if you want to buy the new one, check if RTS and/or DTR are present. On my old USB-to-TTL232 interface neither of those was there, but it uses a PL2303 driver that exposes RTS on pin 3 and DTR on pin 2 so I had to solder a wire directly on IC pin.

The output of RTS (or DTR) pin needs to be connected to the Base of a BJT transistor that controls the current flow through a relay:

If you don’t want to build that part you can use one of these: https://amzn.to/2QDpRQF or https://amzn.to/2QycYHM.

This is the code to SET the RTS pin:

#include <fcntl.h>
#include <sys/ioctl.h>
#define PORT "/dev/ttyUSB0"
main() {
  int fd;
  fd = open(PORT, O_RDWR | O_NOCTTY);
  ioctl(fd, TIOCMBIS, TIOCM_RTS);
  close(fd);
}

and to CLEAR the RTS pin:

#include <fcntl.h>
#include <sys/ioctl.h>
#define PORT "/dev/ttyUSB0"
main() {
  int fd;
  fd = open(PORT, O_RDWR | O_NOCTTY);
  ioctl(fd, TIOCMBIC, TIOCM_RTS);
  close(fd);
}

To use DTR instead of RTS change TIOCM_RTS to TIOCM_DTR.

Compile it with gcc:

gcc set-rts.c -o set-rts

or run in with tcc:

tcc -run set-rts.c

Here’s mine:

Leave a Reply

Your email address will not be published. Required fields are marked *