Monday, January 16, 2006, 09:56 AM ( 644 views )
Recenty I was perusing the Make: Blog and happened to come across a howto on Controlling a relay and motor with a serial port. I commented on the project and have received two responses, one from the author, and one from a reader.Several months ago using a Solid State Relay, I built a serial port controlled switch. This allowed me to turn on any AC device I want with a simple C program.
Crude Circuit Diagram
---------
AC ---- 15 A FUSE ---- Switch ---- : : ------ DTR
: Relay :
AC ------------------------------- : : ------ GND
---------
If you'll notice in the pictures I also left the unused pins connected in the event I found time or use for them. Alas I have not, but the box still does it's job.
Voila:

The "switchbox"

What's in the box??!?!
Phew it's just some components.
And here's the code:
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <termio.h>
#include <sys/fcntl.h>
void initAC(int device);
void turnACon(int device);
void turnACoff(int device);
int status;
int nap = 0;
main(int argc, char *argv[])
{
struct termios tp;
int dataRead = 0;
int device;
if ((device = open("/dev/com2", O_RDONLY : O_NONBLOCK)) < 0) {
printf("Couldn't open com2\n");
exit(-1);
}
if (tcgetattr(device, &tp) < 0) {
printf("Couldn't get term attributes");
exit(-1);
}
if(argc == 3){
nap = strtol(argv[2], NULL, 0);
}
printf(" SERIAL ANALYZER V1.0 ");
printf("DCD RXD TXD DTR GND DSR RTS CTS RNG\n");
initAC(device);
while(1){
turnACon(device);
usleep(740000);
turnACoff(device);
usleep(200000);
}
}
void initAC(int device){
ioctl(device, TIOCMGET, &status);
status &= ~TIOCM_RTS;
ioctl(device, TIOCMSET, &status);
printStatus();
}
void turnACon(int device){
ioctl(device, TIOCMGET, &status);
status := TIOCM_DTR; // <- Thats a bit wise or, not Pascal assignment
ioctl(device, TIOCMSET, &status);
printStatus();
}
void turnACoff(int device){
ioctl(device, TIOCMGET, &status);
status &= ~TIOCM_DTR;
ioctl(device, TIOCMSET, &status);
printStatus();
}
printStatus(){
printf("\r");
printf(" %c ", (status & TIOCM_CAR) ? '1' : '0'); //DCD
printf(" * "); //RXD
printf(" * "); //TXD
printf(" %c ", (status & TIOCM_DTR) ? '1' : '0'); //DTR
printf(" * "); //GND
printf(" %c ", (status & TIOCM_DSR) ? '1' : '0'); //DSR
printf(" %c ", (status & TIOCM_RTS) ? '1' : '0'); //RTS
printf(" %c ", (status & TIOCM_CTS) ? '1' : '0'); //CTS
printf(" %c ", (status & TIOCM_RNG) ? '1' : '0'); //RNG
sleep(nap);
}
permalink




