How to use a Relay with Arduino Uno

Wouldn’t it be great if you could operate your switch without physically toggling it on and off?  Well, relays are one of the best ways of doing this. A relay is a switch, controlled by an electromagnetically charged coil. When the coil charges up, it toggles the switch into its open or closed position.

If you wish to control your lights in your home via a Wi-Fi then a relay switch and an Arduino microcontroller will be good enough to venture the realm of the home automation!

In an electromechanical relay, we see a low-current circuit toggled to energize an internal coil. This low-current coil, when energized, will create an electromagnetic field around itself that toggles a higher-power switch. Mains Power can and will kill you if you do not know what you are doing, we do not advise/recommend you go manipulating 240V AC power directly from the wall. The relays may be able to control the voltage/current loads, but it is simply too dangerous to play around with.

HOW ARE WE GOING TO USE RELAY WITH ARDUINO UNO?

We are going to be using a small, 5V relay to switch a higher power load with our Arduino. As with most of the things we do here, first, we are going to show you the barebones basics of interfacing with a relay. That way you can apply the logic of using this component to your circuits later! So, our relay is just going to be switching a load today, but the idea itself is certainly scalable. We are going to use a transistor to control a relay which will switch a LED on and off; LED will be on a separate circuit with its power supply.

SETUP

Grab the following components:

  • Arduino Uno
  • SPDT Relay
  • Breadboard
  • LEDs

CODE

Run a basic code on the Arduino IDE.

const int relayPin = 2;     // use this pin to drive the transistor
const int timeDelay = 1000; // delay in ms for on and off phases

void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
}


void loop()                    
{
  digitalWrite(relayPin, HIGH);  // turn the relay on

  delay(timeDelay);              // wait for one second

  digitalWrite(relayPin, LOW);   // turn the relay off

  delay(timeDelay);              // wait for one second
}

You should be able to hear your relay clicking away as the mechanical components tick over every second, essentially you can have any circuit in place of the 2 LEDs, and your relay will be able to handle switching the current. Of course, it still depends on the rating of the relay itself, but the idea is sound!

sarah ali

sarah ali

Sarah is a passionate writer and blogger. As an early adopter, she enjoys trying out new social media and Internet tools along with WordPress plugins and Web apps.
sarah ali

Leave a Reply

Your email address will not be published.