Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

Lesson 30: Relay Module

In this lesson, you’ll learn how to use an ESP32 Development Board to control a one-channel relay module. We’ll cover turning the relay on and off in a loop, with a 3-second delay between each state change. This project provides hands-on experience with digital output operations in embedded systems, making it ideal for beginners entering the realm of ESP32 and relay modules.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Universal Maker Sensor Kit

94

Universal Maker Sensor Kit

You can also buy them separately from the links below.

Component Introduction

Purchase Link

ESP32 & Development Board (ESP32 Board)

BUY

Breadboard

BUY

5V Relay Module

-

RGB LED Module

-

Wiring

../_images/Lesson_30_Relay_esp32_bb.png

Code

Code Analysis

  1. Setting up the relay pin:

    • The relay module is connected to pin 25 of the ESP32 Development Board. This pin is defined as relayPin for ease of reference in the code.


    const int relayPin = 25;
    
  2. Configuring the relay pin as an output:

    • In the setup() function, the relay pin is set as an OUTPUT using the pinMode() function. This means the Arduino will send signals (either HIGH or LOW) to this pin.


    void setup() {
      pinMode(relayPin, OUTPUT);
    }
    
  3. Toggling the relay ON and OFF:

    • In the loop() function, the relay is first set to the OFF state using digitalWrite(relayPin, LOW). It remains in this state for 3 seconds (delay(3000)).

    • Then, the relay is set to the ON state using digitalWrite(relayPin, HIGH). Again, it remains in this state for 3 seconds.

    • This cycle repeats indefinitely.


    void loop() {
      digitalWrite(relayPin, LOW);
      delay(3000);
    
      digitalWrite(relayPin, HIGH);
      delay(3000);
    }