Anth's Computer Cave Tutorials

Use a relay from your Arduino

Today I'll connect a relay and have the Arduino control a 240V lamp.


We've covered building your own relays and using them from your Raspberry Pi, now we'll look at using retail relays with an Arduino.

These relays are just a couple of bucks on ebay and they are easy to use.

They take a 5V signal from the Arduino and activate a larger voltage, generally up to 240V at 10Amps.

Connections

If you are only using one or two of these you can probably power, and activate them, directly from the Arduino pins, like the image below.

In general, though, you are better to power the relay from a separate 5V power source and use the Arduino to activate it. This is because the 5V pin on the Arduino may not provide enough current to power the relay units.

The diagram below shows a relay powered from another source. Note that the GND from the external power needs to connect to both the relay and GND pin on the Arduino.

On the left side of the diagram you can see the 240V wires. Only one of these connects to the relay. One end connects to COM, the other to either NO or NC.

Normally to have the light off by default you would connect to NO, which stands for "Normally Open". The way I am activating these (with the Arduino GPIO set as an output), they work in reverse. When you set the GPIO pin HIGH, it turns the relay off. Set low, it turns the relay on.

To counter this I have connected the other end of the 240V wire to the NC, or "Normally Closed" terminal. The lamp now switches on when the Arduino pin is HIGH.

The Arduino sketch

Below is a sketch to turn the lamp on and off every five seconds. Hardly useful, I know, but it should give you an idea of how to create your own switching functions.

// Arduino relay sketch

int relay = 9;

void setup() {                
  // set the digital pin as an output.
  pinMode(relay, OUTPUT); 
  digitalWrite(relay, LOW);
  delay(1000);
}

// the loop runs over and over until you go insane:
void loop() {
  digitalWrite(relay, HIGH);   // turn the lamp on
  delay(5000);               // wear sunglasses for five seconds
  digitalWrite(relay, LOW);    // turn the lamp off again
  delay(5000);               // sit in the dark for five seconds
}

Cheers

Anth

Previous: Connect an Arduino to a Raspberry Pi via a serial

Related:Build a relay box to switch lights with Raspberry Pi


_____________________________________________


Comments

Leave a comment on this article



About the Author

Anthony Hartup, creator of AAIMI, Estimcad and Anth's Computer Cave.
Anthony Hartup runs the AAIMI Project, a Python machine-interface platform.
He also codes for the Estimcad Project and ControlCadGUI.


Search the Cave with AaimiClip