OVERVIEW
This might seem like a very simple tutorial, and in a way it is!
But knowing how to connect and use these small Relay Modules the right way is important since we are playing with High Voltage (120v) and we don’t want to damage our Arduino, or ourselves…
In this tutorial we will use an IR Motion Sensor to detect movement and turn on a 120V light using the relay module.
*Disclaimer:
Since we are using LINE VOLTAGE of 120V, you should take the necessary precautions when dealing with high voltage. If you are worried or not sure, you should not proceed any further…
You have been warned!
PARTS USED
Relay Module
Motion Sensor
Arduino UNO
These are Amazon affiliate links...
They don't cost you anything and it helps me keep the lights on
if you buy something on Amazon. Thank you!
CONNECTIONS
We connect the IR Motion sensor “OUT” to Pin 4 and the Relay “IN1″ to Pin 8.
The light bulb has one of the 120V wire spliced to connect the end connected to the power plug to the COM(Common) Pin of the Relay module and the one going to the lamp is connected to the NC(Normally Closed) Pin.
We use a breadboard to connect the VCC and Ground to both modules from our UNO, but we connect a 1N4007 rectifier Diode to the VCC line of the Relay Module to allow the current to go only one way.
One important thing that is sometime forgotten is to use a Rectifier Diode when switching High Voltage.
Some Relays have this protection integrated, but these Diode are so cheap, why not add another layer of protection to our circuit.
Putting the Diode between the Relay and Arduino, will protect us from power surges when the Relay switches since the Diode only allows current to flow one way.
For more information about the Relay module connections and IR Motion sensor jumper settings, please watch our Tutorial video..
THE CODE
No libraries or complicated stuff here…
All we are doing is looking at the Pin the IR Motion sensor is connected to.
If the Pin 4 is LOW, it means no motion is detected, if HIGH then motion is detected.
We are using a WHILE loop to check if Pin 4 is HIGH, if yes then we make Pin 8 HIGH turning on the Relay module.
If Pin 4 is LOW, then we make Pin 8 LOW turning off the relay.
As always please watch our Tutorial video for more information.
int irmotionPin = 4; // Pin of IR Motion Sensor
int relayPin = 8; // Pin of Relay Module
void setup(){
Serial.begin(9600);
pinMode(relayPin, OUTPUT); // Set Pin connected to Relay as an OUTPUT
digitalWrite(relayPin, LOW); // Set Pin to LOW to turn Relay OFF
}
void loop(){
while (digitalRead(irmotionPin) == HIGH) { // If Motion detected
digitalWrite(relayPin, HIGH); // Turn Relay ON
Serial.println("Relay is ON");
delay(500);
}
digitalWrite(relayPin, LOW); // Turn Relay OFF
Serial.println("Relay is OFF");
delay(500);
}
TUTORIAL VIDEO
DOWNLOAD
Copy and paste the above code in the Arduino IDE to program your Arduino.
Comentarios