Example Code for Arduino-Relay On/Off Control
This article is a complete guide to controlling a relay using Arduino, featuring detailed instructions on setup, necessary hardware and software, a wiring diagram, and sample code to automate the relay's on/off function every two seconds.
Hardware Preparation
- DFR0017 Digital 5A Relay Module (SKU:DFR0017 x 1)
- DFRduino UNO R3 with IO Expansion Shield and USB Cable A-B (SKU:DFR0216-2 x 1)
Software Preparation
- Development Tool: Arduino IDE (version unspecified). Download link: Arduino IDE
Wiring Diagram

Other Preparation Work
- Connect the relay module to Arduino according to the wiring diagram.
- Ensure Arduino is powered and connected to your computer.
Sample Code
//Arduino Sample Code
//www.DFRobot.com
//Last modified on 14th March 2012 by HJS
//This code has been updated to work with the sample code provided in the Wiki
int Relay = 3;
void setup()
{
pinMode(13, OUTPUT); //Set Pin13 as output
digitalWrite(13, HIGH); //Set Pin13 High
pinMode(Relay, OUTPUT); //Set Pin3 as output
}
void loop()
{
digitalWrite(Relay, HIGH); //Turn on relay
delay(2000);
digitalWrite(Relay, LOW); //Turn off relay
delay(2000);
}
Result
Every two seconds, LED will be turned on and off.
Additional Information
The relay output state is indicated by a built-in LED for user convenience.
Was this article helpful?
