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
Here is a diagram of the circuit:
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.
The final product:

Update: Joe sent in his version of a
serial port relay. He uses a solid state relay instead of the transitor/relay setup I have. That makes things a lot simpler.
Resources:
Serial Programming Guide for POSIX Operating Systems
Controlling Hardware with ioctl
Controlling Devices with Relays

As production increases in
As production increases in the foreign market, qualified and experienced domestic workers leave or are forced out of their jobs, often permanently leaving the industry. At some point, dramatically fewer domestic workers are left who are qualified to perform the work
broken link
the link to relay.c is broken, could you check it?
Thanks,
ed
broken link
the link to relay.c is broken, could you check it?
Thanks,
ed
how to control 2 relays?
The given circuit diagram used to control only one relay. but how to use it to control 2 relays? also pls send the VB version and c Version of program to my id to use it with windows not unix
more pic
Please send more pictures
thank you
error
I am totally new to this and i am not sure how to set this up there is a few miner changes the only connection that i am using is a usb to 15 pin 2 column connector and i am having a bit of trouble with c++ programing please help- this is the error log after compiling in dev-c++
-\Documents and Settings\Administrator\Desktop\relay.c C:\Documents and Settings\Administrator\Desktop\C sys/ioctl.h: No such file or directory.
-\Documents and Settings\Administrator\Desktop\relay.c C:\Documents and Settings\Administrator\Desktop\C termios.h: No such file or directory.
- C:\Documents and Settings\Administrator\Desktop\relay.c In function `main':
-18 C:\Documents and Settings\Administrator\Desktop\relay.c `O_NDELAY' undeclared (first use in this function)
- (Each undeclared identifier is reported only once
- for each function it appears in.)
-31 C:\Documents and Settings\Administrator\Desktop\relay.c `TIOCMSET' undeclared (first use in this function)
-32 C:\Documents and Settings\Administrator\Desktop\relay.c `TIOCMGET' undeclared (first use in this function)
-33 C:\Documents and Settings\Administrator\Desktop\relay.c `TIOCM_DTR' undeclared (first use in this function)
-37 C:\Documents and Settings\Administrator\Desktop\relay.c `TIOCM_RTS' undeclared (first use in this function)
I am using a mac with vmware fusion running xp
redriderusa96@hotmail.com
The code was written to run
The code was written to run on linux with the gcc compiler. It looks look you are running windows.
Your best bet is to try to find a library that will let you directly control the lines on windows. You might try:
http://www.wcscnet.com/CdrvLNBro.htm
I have found that it is usually easier to use an 8 bit chip like an arduino. You talk to the chip over standard serial and the chip controls your relays.
thanks
chad
No need to purchase an
No need to purchase an expensive 3rd party library! If you're coding in "c" on a more recent NT-based Windows OS (e.g. Windows 2000, XP, Vista), you'll need to use the win32 APIs to use the serial port; normal "user-land" programs are not allowed to talk directly to the serial-port in NT-based Windows OSes, only the kernel is allowed to do that. This means that functions like "outp", "outportb", "bios_serialcom" etc. don't work. Instead, you have to #include windows.h and winbase.h, then use win32 APIs such as "CreateFile" and "EscapeCommFunction". For example, to control the DTR line, you could use this code for a win32 console application:
#include stdio.h
#include conio.h
#include twindows.h
#include winbase.h
void main ()
{
HANDLE SerialPort;
int Error, CallStatus;
SerialPort = CreateFile(TEXT("COM1"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (SerialPort==INVALID_HANDLE_VALUE)
{
Error=GetLastError();
printf("error opening serial port! :-(\nError code: %i\nPress any key to exit...\n", Error);
getch();
}
else
printf("serial port open\n");
CallStatus=EscapeCommFunction(SerialPort,CLRDTR);
if (CallStatus==0)
{
printf("error clearing DTR of serial port\nPress any key to exit...\n");
getch();
}
else
{
printf("DTR cleared\nPress any key to exit...\n");
getch();
}
}
more info can be found at MSDN
Need Help.
Hi Guys.
This thing looks cool, but i wanted to know if any of you knows how to timer it.
example. i want the motor run for 5 seconds and then off. and i want to control it in both ways the motor, forward and backward.
i would appreciate it if any of you guys can teach me how.
thanks a lot. cool page. cool people.
Steve
FREMONT, CA, USA
estchen@gmail.com
In the source, Just add a
In the source, Just add a delay command with the Millisecs you want the pin to stay high, between the set high and set low commands.
Thanks for the idea...
I built one too: http://www.nsit.info/commcontrol/
The VB.Net 2005 code is there as well.
vb2005 .net program for Windows XP and .Net 2.0
Ahhh--serial ports. They're going away, but most of us still have at least one in the form of a header on our motherboards--which I'm making use of thanks to this blog! Special thanks to the anonymous poster who provided this: http://www.nsit.info/commcontrol/. The program I wrote is largely based on it and controls an Elk-924 sensitive-trigger relay ($12.14 through Amazon) which sends power to a hard disk array within my computer case.
One has to apply a registry tweak to prevent the triggering action during boot up:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\ACPI\PNP0501\4&2658d0a0&0\Device Parameters]
"SkipEnumerations"=dword:ffffffff
Before you apply this make sure the "4&2658d0a0&0" key name is the same on your machine. Apply it only to the key corresponding to the port you wish to use (the name "com1" or "com2" will appear within the values.)
This registry tweak disables the serial port plug-and-play enumeration, which raises and lowers RTS and DTR during boot-up and trips the relay. So don't use it if you need to use other devices with the serial port you intend to use.
I use a raised RTS signal to trigger my relay (no looping required in VB.) This is pin 7 on my motherboard header and all db-9 serial ports.
The code was compiled on Visual Basic Express 2008 (free from Microsoft). This package will install about 700 MB worth of stuff, including .Net 3.5, but the code still works with .Net 2.0. Hint: configure three buttons on the form first, add a notifyicon1 from the toolbox, then paste the code. I can provide an executable in a zip file (for use on COM1) to those who request it.
Imports System.IO.Ports
Public Class Form1
Public s As New SerialPort
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
s.Close()
s.PortName = "COM1"
s.BaudRate = 9600
s.DataBits = 8
s.Parity = Parity.None
s.StopBits = StopBits.One
s.Handshake = Handshake.None
s.Open()
s.RtsEnable = True
NotifyIcon1.ShowBalloonTip(2710)
Minimizetotray()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If s.IsOpen Then GoTo 1
s.Open()
1: s.RtsEnable = True
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
s.RtsEnable = False
s.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If s.IsOpen Then GoTo 2
s.Open()
2: s.RtsEnable = False
s.Close()
s.Dispose()
NotifyIcon1.Dispose()
End
End Sub
Private Sub Minimizetotray()
Me.Visible = False
Me.ShowInTaskbar = False
NotifyIcon1.Visible = True
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If e.CloseReason = CloseReason.UserClosing Then
e.Cancel = True
Me.Visible = False
Me.NotifyIcon1.Visible = True
End If
End Sub
Private Sub NotifyIcon1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
Me.Visible = True
Me.ShowInTaskbar = True
End Sub
End Class
Zip file
hi,thanks for the code,but i'm not a great porgrammer...i read but not understand..can u send me the zipwith the executable please? to dannicantero@yahoo.com.ar ,thanks in advance!!
re: vb2005 .net program for Windows XP and .Net 2.0
The above code has some creature comforts--namely starting hidden, a task tray icon, a balloontip and closing to the task tray. For the most minimal functionality just leave off the last three subs, delete these lines in the first sub:
NotifyIcon1.ShowBalloonTip(2710)
Minimizetotray()
And delete this line: NotifyIcon1.Dispose()in the last remaining sub.
But the creature comforts are what really makes this hum for me!
Executable VB file
Hello. Thanks for the code. I am trying to teach myself VB at the moment. Could you please email me the VB file and executable file? My email address is miltonsbells@att.net.
Thanks
Milton
www.miltonsbells.com
thanks for posting your
thanks for posting your code. I'll have to give it a try.
VB.Net 2005 App to control Serial Port
I just finished a VB 2005 app to control this circuit. I did some testing and I can control a 30Amp accessory relay that is used in automotive applications. This app turns the Com1 ports DTR.Enable = True or False to control the relay.
If anyone wants this app I can zip it up and send it your way. This stuff is really cool.
I can also convert it to a C# app if someone needs it.
My app does everything in code using no Serial Control or MSComm control. Very simple and straight forward.
Cheers
Serial port data !!
if i get that sample code ,that will be very use full for me
thanks
Dinu
Need a copy of that program pls
Hi Mr.Ron,
I too need that vb.net 2005 application.
can u send it to me (Email: jcb871@gmail.com)
I hav a doubt too...
did u use the same circuit which is given above?
pls reply to my mail. Its a bit urgent
Code to control the circuitry
Hello Ron Kessler
can you please mail me the code you have written to control that circuitry on mutahirakhan@hotmail.com
I have a circuitry very similar to the one described in this forum. I am also controlling the relays through the serial port.
But I am not a good programmer I am unable to send data from .net to the microcontroller.
can you please mail me the code ASAP!
Thank you so much in advance
VB 2005 app
Dear Ron,
I go thru this site by chance, I am really interested with your VB 2005 app and hope I can use it for my project which is control things using serial port
Can you send it to my email address please?
Thanks
Rich
hi.. i felt like u can help me
Hi Ron...
im in need for VB2005 code to send signal to my parallel port... can u help me out
my mail id is dan_inurheart@yahoo.co.in
rs232 com port
I would like to control the rs232 port, also the individual pins if possible, and for in and output. May I benefit from your experiences and results? I am new in VB 2005 / VB.Net.
serial port using vb.net
I am doing a project based on serial port RS-232 to run a motor for a demo. So please send the vb.net code to complete the project successfully!!!
with Regards
M.Mohamed sha
your Vb2005
Can you send this code to me please. I need it as soon as possible. thanks
.exe program
Hi
I am not so good programmer and I would like to make this kit working like this: each time I run an .exe file i would like to switch on the relay just once (lets say for half a second)and then release it. Can you please help me? If it is possible can you make for me this .exe file because I am not getting well with programming and compilers... :-(
Thank you again
Pit
MSComm control
Dear Cheers,
I am software developer and i need to control the relay through comport in vb.net 2005,can you help me please.
azam khan
software Developer
Pakistan
project In VB6
can any one write code for VB6 since I have no idea c laguage.
Thanks
re: Project in VB6
You may not be able to do this in VB. It requires low level access to the serial port. Languages like VB abstract a lot of that stuff and don't always allow you low level access.
If you need to use VB, I would suggest you get an arduino microcontroller. You can easily communicate with it and VB over serial. Tons of info for that on the web. Then have the arduino control the relay.
help me in my project please
how do i control the voltage output of serial port to turn on or off the dc motor?
and i want to use visual basic 6.0 as my programming language.can you send me a source code to control the dc motor?tnx...please reply me...
I need some help
Hello,
I've built the circuit, but somehow the relay just switches ON. Then, it ignores the DTR I think. Even if I remove the db9 from the serial port, it stays on. Only when I remove the power from the circuit, it switches off.
Any ideas of what I could have done wrong ?
Thanks =)
help me to run
if u run the program previously and it swicthing on then help me how u done it. from where u runing it and tell me command to run itand if possible send me code of ur program.
i am runing short of time.please.............
re: I need some help
First thing would be to narrow stuff down. Unplug it from the serial port and remove the relay. Now take a meter and see if you have current from the transistor (where it connects to the relay). You shouldn't. Then apply current to the diode (where DTR connects). The circuit should open then. If then works fine, then connect up DTR and try the same thing.
One thing I have noticed is that reed relays like I use, can fuse open very easily. If you draw too much current through them (like when a motor starts up) it can fuse the contacts open. So you might check that.
the role of the diode in your circuit..
I saw that after DTR pin 4 there is a diode and then the resistor.. I started to learn electronics by my own and I chose this project as my first project (well.. not exactly this one, but this one:
http://www.instructables.com/id/EHVZ11WRT7EPD7QSQ9/
However, the author of the project above was saying he was inspired by your project so I took a look here. Indeed, the schematics look very much alike. I was wondering why you use that diode before the resistor..
Thank you,
Ionut
re: the role of the diode in your circuit..
The diode makes sure that no current flows back into the serial port pin. It is more of safety feature. You can read on on diodes at http://en.wikipedia.org/wiki/Diode
reply
Not that I didn't read the article with interest, but are you aware of a ifplugd (http://www.stud.uni-hamburg.de/users/lennart/projects/ifplugd/), a nifty little tool that does exactly what you want. On my laptop I have mandrake, I configure the network to not start on boot up. Furthermore, I start ifplugd somewhere along the boot-up sequence. As soon as ifplugd sees a cable, it will run your distributions ifup command, and if it detects the cable is gone: ifdown. nexium
precompiled code
i am having trouble compiling the c program. could someone please direct me to a compiled binary file?
thanks,
frank
librarys for compile
Sorry for the trivial question, but i am trying to compile the relay.c using the borland C compiler, but (being new to C) I cannot work out where all the include files should come from. Google is not being kind, and I've tried a few random files with no success
Error E2209 ..\relay.c 2: Unable to open include file 'sys/ioctl.h'
Error E2209 ..\relay.c 6: Unable to open include file 'unistd.h'
Error E2209 ..\relay.c 9: Unable to open include file 'termios.h'
etc (yes i put the cgf file in as per the readme...)
Thanks
Leave the relay on?
Is it possible to edit your program so that i could make 2 seperate exe's to say "turn the relay on" and "turn the relay off"?
I need to script some tasks for an undefined amount of time, So need to close the relay, run the rest of the script, and then open the relay again.
Sorry i dont understand C that well yet (batch has sufficed until now!). I guess i could re-code everything into the C program, but would rather be able to call it on and off...
Short of that i'll need to control 4 channels and have latching relays (or latching circuits), which cant be done by serial?
Serial Port Control
Hi There
Have just came accross this thread and have become interested in connecting my project to be controlled by a computer via its serial port. I would like to be able to write a program to turn the DTR pin(4) high for 1 second everytime I run the program. The program would need to be an .EXE(I think). Which is the best lang to do this in(I have little experience but willing to learn)eg visual basic, C++ etc. Are there any tutorial sites, books etc I could get. Any pointers/help would be appreciated.
Many Thanks
Paul.
The c language is simpler
The c language is simpler than c++. Considering that is the language of the sample program that does exactly what you want, that is the best way to go.
The sample program uses a delay of 2 seconds. To make it do what you want, change the 'sleep(2);' to 'sleep(1);'.
Then you will need a c compiler.
You can get a borland C compiler free. Try this website:
http://www.johnsmiley.com/cis18.notfree/smiley029/smiley029.htm
It is a c++ compiler, but if your file has a .c extention, it compiles as c. Type in bcc relay.c and it will compile and you will get your exe.
Bill
circuit not working
i am not able to use this circuit.
when i compile and run ./relay /dev/ttys0 its showing
ar-2:/dev/ttys0:input/output error
circuit not working
I also couldnt get this circuit to function properly, I used VB to control the hi-lo of DTR
Initially, the dc motor would run (without doing anything) and then when DTR is set to hi, the motor would start to run slowly, however, when DTR is set to lo again, the motor would not run to the same RPM as before (no change absolutely).
I don't think your circuit works by the way
circuit
It sounds like you are using a normally closed relay instead of a normally open one. When you intitally power it up, the relay should not be send any current to the motor. It sounds like you have have default closed relay and are drawing too much current through it. If it slow down when you set DTR high, it sounds like it is trying to open the relay and shut off power to the motor. If you are drawing too much power through the relay it can weld the relay open or shut. Try testing the relay with a meter and see if it opens and closes when the DTR is set high or low. Try testing your relay with it being unhooked from the circuit. The relay contacts may be burned and ruined.
A suggestion
I did a similar project a while ago so that I could get physical alerts from email.
The approach is similar, take a serial port and use one of the flags. Then use a relay. Rather than a mechanical relay, I used a solid state relay. Furthermore I didn't need the transistor and 9V battery. Also I was able to switch AC power (25A worth!).
So the sequence went like this. Email with certain subject was received. The email rule invoked a program that set the DTR flag. The relay turned on and voila the $10 rotating beacon light turned on.
I hope this helps you in your quest to control the world.
Feel free to contact me with questions:
josephpabbey yahoo com
Joes version using a solid state relay:
http://stats.the-abbeys.com/blog/index.php?entry=entry060116-095620
I'm looking at controlling
I'm looking at controlling about 16 individual relays, ideally through the serial port, what would be the cheapest way around this. i've seen devices that you can buy, but i'm sure it's possible to build one much cheaper
You won't be able to control
You won't be able to control that many directly from the serial port. A better idea would be to control a PIC from the serial port, then have the PIC control the relays. You can get a basic stamp module for about $45. You could easly control the Basic Stamp through with a serial port, then the basic stamp I believe has 16 I/O pins which could be used to control your relays.
i'm aware that it won't be
i'm aware that it won't be direct.
http://www.hobbybotics.com/serialrelay1a.htm
two of these could be knocked up fairly cheaply, been searching for hours and this seems to be the best home-brew project i've found so far
Post new comment