How to turn on a SPDT RELAY with arduino

In this tutorial, we will learn how to control an SPDT relay module with an Arduino Uno using a push button as a toggle switch. Each press of the button will change the state of the relay: if the coil is off, it will turn on and stay on until the button is pressed again to turn it off. 

 📝 Required components

  • 1 x Arduino Uno (or compatible board)
  • Push button
  • LED/Lamp (any color)
  • 220Ω resistor (for the LED)
  • Power Supply
  • Breadboard 
  • Jumper wires

Step 1: Wiring the Electronics 

1. Connect VCC of the relay module to Arduino 5V. 
2. Connect GND of the relay module to Arduino GND. 
3. Connect the IN pin of the relay module to Arduino digital pin 8. 
4. Connect one leg of the push button to Arduino digital pin 7. 
5. Connect the other leg of the button to GND. 
6. Also connect that same leg of the button directly to 5V. 
 
When the button is pressed, pin 7 reads HIGH; when released, it reads LOW. 

🖥️Step 2: Writing the Code

This is the complete code to use the button with Arduino:

				
					const int buttonPin = 7;      // Pin connected to the button 
const int ledPin = 8;        // Pin connected to the LED 
 
int buttonState = 0;          // Variable to store button state 
 
void setup() { 
  pinMode(buttonPin, INPUT);  // Set button pin as input 
  pinMode(rlay, OUTPUT);    // Set LED pin as output 
} 
 
void loop() { 
  buttonState = digitalRead(buttonPin); 
 
  if (buttonState == HIGH) { 
    digitalWrite(relay, HIGH); // Turn LED on 
  } else { 
    digitalWrite(relay, LOW);  // Turn LED off 
  } 
} 
				
			

🔎 Breaking down the Code

Let’s review the code section by section:

				
					buttonPin
				
			

 Is used to detect the button press.

				
					ledPin
				
			

 Controls the LED.

				
					pinMode()
				
			

 Sets up the pins as input or output.

				
					digitalRead()
				
			

 Checks if the button is pressed.

				
					digitalWrite()
				
			

Turns the LED on or off based on the button’s state. 

🛠️Step 3: Troubleshooting 

 

Relay does not change state:

  • Check that the relay module VCC and GND are properly connected.

  • Ensure a stable 12V supply and common ground. 
es_ES