How to use a 5V Relay with Arduino
How to use a 5V Relay with Arduino
INTRODUCTION
A relay is an electrically operated switch. Many relays use an electromagnet to operate a switch mechanically, but other operating principles are also used, such as solid-state relays.
APPLICATIONS
Relays are used where it is necessary to control a circuit by a separate low-power signal, or where several circuits must be controlled by one signal. Relays are also used on high voltage circuits.
WIRING DIAGRAM
VCC – 5V
GND – GND
OUT – Digital Pin 2
CODE
const int relayPin = 2; //the base of the transistor is attached to String comdata = ""; int lastLength = 0; void setup() { pinMode(relayPin, OUTPUT); //initialize the LED as output Serial.begin(9600); // start serial port at 9600 bps: while (! Serial); Serial.println("Please input your command to control this Lamp:"); //print message on serial monitor } void loop() { //read string from serial monitor if(Serial.available()>0) // check if data has been sent from the computer { comdata = ""; while (Serial.available() > 0) { comdata += char(Serial.read()); delay(2); } Serial.println(comdata); } if(comdata == "on") { digitalWrite(relayPin, HIGH);//turn the lamp on } else if(comdata == "off") { digitalWrite(relayPin, LOW);//turn the lamp off } else { Serial.println("Please input correct command !"); delay (20000); } }
END RESULT
Open the serial monitor. Type “on” to turn ON the lamp, and type “off” to turn OFF the lamp.
ADDITIONAL RESOURCES
https://www.circuitbasics.com/setting-up-a-5v-relay-on-the-arduino/
https://www.hobbyist.co.nz/?q=interfacing-relay-modules-to-arduino