Example Code for Arduino-Basic Relay Switching
Last revision 2026/01/07
This article offers a comprehensive guide on using Arduino for basic relay switching, detailing hardware and software requirements, wiring diagrams, and sample code for controlling appliances safely.
Hardware Preparation
- Arduino UNO
- Relay Shield For Arduino V2.1
- Power Supply:7~ 12V
Software Preparation
Arduino IDE
Library installation
Wiring Diagram
In this sample connection diagram it shows how LED can be controlled via relays, while this is a bit of overkill for controlling LEDs its only meant to be an example. These relays can be used to control lamps, or some other mid-voltage range appliances.

Other Preparation Work
We will use "NO" for our example, using "NC" will simply reverse the logic, as explained above.
We recommend using a swappable cable to do this with, as using a relay requires you to perform some minor surgery on the appliance's cable. To plug in an appliance such as a lamp: Cut and strip a portion of the positive wire so that you end up with two ends of the wire as shown in Figure 2.
The relay should have the positive wire of the device being used connected to "COM" and to "NO" as shown in figure 2, and any digital signal pin on the arduino end (For example pin 13). Sending a digital high or a "1" will trigger the relay. Sending a digital low or "0" will disable the relay.
It needs an external power supply to drive the xbee module and relays. Suggested: 7-12V.

Sample Code
byte relayPin[4] = {2,7,8,10};
//D2 -> RELAY1
//D7 -> RELAY2
//D8 -> RELAY3
//D10 -> RELAY4
void setup(){
for(int i = 0; i < 4; i++) pinMode(relayPin[i],OUTPUT);
}
// an sample to switch the 4 relays
void loop(){
int i;
for(i = 0; i < 4; i++) digitalWrite(relayPin[i],HIGH);
delay(1000);
for(i = 0; i < 4; i++) digitalWrite(relayPin[i],LOW);
delay(1000);
}
Result
The 4 relays should be turned on and off every second.
Additional Information
Please be vary carful not to play with live circuits! 120V or 220V should not be taken lightly. Make sure the appliance to be tinckered with is unplugged from mains. DO NOT CONNECT IT TO THE WALL WHILE MESSING WITH THE CABLE !
Was this article helpful?
