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 will learn how to use a relay and an Arduino Uno to control a traffic light module. We’ll demonstrate how to turn the red light of the traffic module on and off using the relay. This project is ideal for beginners in Arduino, providing hands-on experience in controlling external modules and gaining a fundamental understanding of relay operations.

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

Arduino UNO R3 or R4

BUY

Breadboard

BUY

5V Relay Module

-

Traffic Light Module

BUY

Wiring

../_images/Lesson_30_relay_module_uno_bb.png

Code

Code Analysis

  1. Setting up the relay pin:

    • The relay module is connected to pin 6 of the Arduino. This pin is defined as relayPin for ease of reference in the code.


    const int relayPin = 6;
    
  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);
    }