Amazon

Friday 10 April 2015

Interfacing with TPL9201 relay driver using a PIC

The TPL9201 is a 8-channel relay driver that uses serial communication. For the purpose of this article, I will be using a PIC16F1782 from Microchip to interface but the code can be used with any microcontroller from the PIC16 family. The C compiler used is from Hi-Tech

To interface with the TPL9201, you need 3 I/O pins from the microcontroller; Chip Select (CS), Data (SDO), and Clock (SCK).

In this example, relays that are used are EC2-5NU from NEC. To activate a relay, you need to send a "1" to the corresponding control register bit of the TPL9201. On the other hand, if you want to release the relay, you need to send a "0".
The control register is illustrated below:

MSB                                           LSB 
IN8 IN7 IN6 IN5 IN4 IN3 IN2 IN1 
 0      0      0     0      0     0      0     0 

INn = 0: Output OFF 
INn = 1: Output ON

Following is the code to activate all 8 relays and then release them.

#include "htc.h"
#include "pic16f1782.h"

#ifndef _XTAL_FREQ
#define _XTAL_FREQ 16000000
#endif

#define CS RA5
#define SCK RC3
#define SDO RC5

void spi_writebit(unsigned char SPI_DATAbit)
{
SDO = SPI_DATAbit;
__delay_ms(1);
SCK = 1;
__delay_ms(1);
SCK = 0;
}

void spi_write(unsigned char SPI_DATA)
{
char Bit_counter;
char Bit_send;

CS = 0;
SDO = 0;
SCK = 0;
__delay_ms(1);

for (Bit_counter = 0;Bit_counter<=7;Bit_counter++)
{
Bit_send = (SPI_DATA>>(7-Bit_counter))&0x01;
spi_writebit(Bit_send);
}
SCK = 0;
SDO = 0;
__delay_ms(1);
CS = 1;
}

void Relay_Control(unsigned char Relay_no, unsigned char Relay_State)
{
if (Relay_State)
Buffer_Value = Buffer_Value | (1<<(Relay_no-1));
else
Buffer_Value = Buffer_Value & (0xFF - (1<<(Relay_no-1)));

spi_write(Buffer_Value);
}

void main()
{
  int Relay_number;

  for (Relay_number = 0;Relay_number<=7;Relay_number++)
Relay_Control(Relay_number,1); //Activate all 8 relays

for (Relay_number = 0;Relay_number<=7;Relay_number++)
Relay_Control(Relay_number,0); //Release all 8 relays
}

No comments: