In this tutorial, we will learn how to interface a relay module with NodeMCU, allowing us to safely control high-power AC devices using a microcontroller.
What We Will Learn in This Section- Understanding how relays work
- Connecting a relay module to NodeMCU
- Writing Arduino and MicroPython code to control the relay
- Safety considerations when working with AC devices
Learning to interface relays with NodeMCU opens up possibilities for home automation and IoT projects. It allows you to control appliances such as lights, fans, and more, using your microcontroller safely and effectively.
Components List (Amazon Affiliate Links)- NodeMCU
- Relay module
- Jumper wires
- AC device (e.g., light bulb)
- Breadboard
- NodeMCU D5 to Relay Signal Pin
- NodeMCU GND to Relay GND
- Relay VCC to External 5V Power Supply
- AC Device to Relay Common (COM) and Normally Open (NO) Pin
int relayPin = D5; // Define NodeMCU pin connected to relay module
void setup() {
pinMode(relayPin, OUTPUT);
}
void loop() {
// Example: Turn on relay when button is pressed
if (digitalRead(D2) == HIGH) { // Assuming D2 is connected to a push button
digitalWrite(relayPin, HIGH); // Turn on relay
} else {
digitalWrite(relayPin, LOW); // Turn off relay
}
}
Code Explanation (Arduino)- int relayPin = D5;: Defines the pin connected to the relay module.
- pinMode(relayPin, OUTPUT);: Configures
relayPin
as an output. - digitalRead(D2): Reads the state of D2 (connected to a push button).
- digitalWrite(relayPin, HIGH): Sets
relayPin
high, turning on the relay.
relay_pin = 14 # Define NodeMCU pin connected to relay module
def setup():
global relay_pin
pin(relay_pin, OUT)
def loop():
global relay_pin
if pin(4).value() == 1: # Assuming pin 4 is connected to a push button
pin(relay_pin, 1) # Turn on relay
else:
pin(relay_pin, 0) # Turn off relay
Code Explanation (MicroPython)- relay_pin = 14: Defines the pin connected to the relay module.
- pin(relay_pin, OUT): Configures
relay_pin
as an output. - pin(4).value(): Reads the state of pin 4 (connected to a push button).
- pin(relay_pin, 1): Sets
relay_pin
high, turning on the relay.
Interfacing relays with NodeMCU provides a flexible way to control high-power devices safely. Ensure proper wiring and observe safety precautions, especially when dealing with AC voltage. Experiment with different appliances and expand your IoT projects using these principles.
Comments