A relay is an electromechanical switch which is used to turn ON or OFF any circuit by using Electromagnet. It is just like practical switch which is drived electronically. By using Electromagnet in Relay we actulay provides isolation hence Relays can be used to power ON or OFF a heavy AC current machine etc. Relays have different ratings and different properties which are not a part of this topic.

Relays and Microcontroller: Microcontroller are intelligent devices but they can’t switch ON or OFF your room fan as they can’t handle heavy current so we use relays to do so. Microcontroller can power ON or OFF an Relay’s Electromagnet. When Electromagnet is turned on or off you can easily hear a sound of ‘tick’ just like a practical room switch. However, there is a glitch here: Relays electromagnet requires heavy current to operate which Microcontroller can’t possible handle. So, we use a transistor to operate the Electromagnet as transistor has a switching behaviour. Please see the circuit diagram below:

Relay drive with AT89C51 using 2N3904
Relay drive with AT89C51 using 2N3904

Equipments Required:

  • AT89C51 Microcontroller
  • 2N3904 or any common switching Transistor
  • Power supply with common ground. 5V for AT89C51 and 12V for Relay
  • Any common diode to be use as freewheeling so to avoid any reversal current from electromagnet.
  • Common Relay
  • 7812 and 7805 Voltage Regulator

Transistor helps in switching action whenever Microcontroller switches ON or OFF a transistor base it shorts the collector and emitter providing switching action and hence current passes from 12V supply to electromagnet to ground resulting ON action of Relay.

One thing to make sure that you must common the grounds of both supplies else transistor won’t be powered ON.

code for the program is as follows you may wanna change it as per your requirement. This code just turns relay ON and OFF after a specific delay

Code:

#include reg51.h

sbit relay_pin = P2^0;

void Delay_ms(int);

void main()
{
 do
 {
  relay_pin = 1; //Relay ON
  Delay_ms(1000);
  relay_pin = 0; //Relay OFF
  Delay_ms(1000);
  }
  while(1);
}

void Delay_ms(int k)
{
 int j;
 int i;
 for(i=0;i<k;i++)
 {
  for(j=0;j<100;j++)
  {
  }
 }
}