A "Serial Relay Controller"
include "modedefs.bas" relay var byte 'relay number storage variable stat var byte 'relay status ON/OFF variable adcon1 = 7 'pins digital I/O, AD = OFF define osccal_1k 1 'set osccal for 1K PIC loop: serin 5,N2400,,relay,stat 'serial in on pin5 if relay = 1 then outr0: if relay = 2 then outr1 if relay = 3 then outr2: if relay = 4 then outr3 goto loop outr0: if stat = 1 then high0 low 0: goto loop high0: high 0: goto loop outr1: if stat = 1 then high1 low 1: goto loop high1: high 1: goto loop outr2: if stat = 1 then high2 low 2: goto loop high2: high 2: goto loop outr3: if stat = 1 then high4 low 4: goto loop high4: high 4: goto loop end
The serial input is on pin #2 (GP5), and uses a single 22K series resistor to limit current to acceptable levels between the PIC & PC serial port.
A synchronization byte of 254 is used to ensure that our outputs aren't triggered by line noise on the serial connection by waiting for the synch-byte before altering the logic state of any output pins.
The rest is very simple. The PIC expects to see the relay number from 1-4 followed by the physical logic state, IE,, 1 or 0 to transfer to the output pins.
Viola..! We now have a serially controlled I/O expander, or a very handy quad serial relay controller for less than the price of that next greasy cheese-burger.......:o]
This project can easily be modified to use GP3 as the serial input pin, and expand the output capacity to 5 output pins.
Notice that we didn't use the TRIS command to setup any of our I/O-pins as outputs/inputs. This is because PicBasic automatically handles this for us when we use commands that affect the I/O-pins such as HIGH 1, LOW 1 and SERIN 5.
Simple NPN Relay Control Circuit:
Below is a simple NPN transistor drive circuit that can be used with this application to control relays. Just duplicate this circuit for each output you wish to control a relay with.
The diode can be just about any spare diode you have in your parts-bin, and should not be left out of the circuit. When the transistor switches off, the collapsing magnetic field of the relay coil will produce a nasty voltage spike. This spike can damage the drive transistor, and sometimes may even blow-up your transistor.
If you have built something similar in the past, and noticed that your transistors seem to keep going bad, it's probably due to not including the fly back diode protection circuit, or you may have the diode in backwards.
Until the next project, have fun, and thanks for stopping by.....:o]