Simple relay operation with Arduino


This is a very simple sketch to show the operation of a relay. Relays for the Arduino are available on small pcb’s and the one I am using is a single relay from Ywrobot. This relay needs 5 volts to operate and has a single changeover switch that can switch 10amps AC at 250 volts. The board has two LED indicators, one to show power is connected and the other to show the relay has been activated. There are only three pins, Gnd (connected to Gnd on the Arduino), Vcc (connected to 5 volts on the Arduino) and a control pin. This control pin connects to a digital I/O pin and a LOW on this pin will switch on the relay. This project used a push switch connected to pin 7 to operate the relay, but pin 7 could be connected as an input from another circuit.

The input pin for the switch is defined as pin 7, but could be any digital pin. The output from pin 8 is used to switch the relay, but any pin could be used.

There are two variables that change how the relay operates, HOLD and LATCH and these can easily be changed. HOLD defines how long the relay will be switched ON for after the input is switched off. In this sketch it is set to 200ms, but can be many seconds. The second variable LATCH if set to TRUE will keep the relay switched ON until RESET is pushed on the Arduino. If it is set to FALSE as it is here the relay will switch off after the time set by HOLD.

/* Simple sketch to show the operation of a push button and relay

Connect a normally open push switch to pin 7 and Gnd on the Arduino

The relay board has three pins, Gnd, Vcc and Control
Connect Gnd to Gnd on Arduino
Connect Vcc to 5 volts on Arduino
Connect Control on relay board to pin 8 on the Arduino

int hold = 200; // time stays on for after button released in ms
boolean latch = false; // if true then the relay remains closed
# define relay 8 // this is the pin used to switch the relay
# define pushSwitch 7 // this is the push switch input

void setup() {
 pinMode(relay, OUTPUT);
 digitalWrite(relay,LOW);  // turn OFF the relay
 pinMode(pushSwitch, INPUT_PULLUP);  //  attaches a resistor from input to Vcc
 digitalWrite(relay, HIGH); // turn off relay


void loop() {

 if (digitalRead(pushSwitch) == LOW ) {  // LOW if pressed
   digitalWrite(relay, LOW);  // relay ON
   delay(hold); // leave relay ON for a short while before turning OFF
 if(latch == false){
   digitalWrite(relay, HIGH);  // relay OFF



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: