Fundamentals 10 min read

Mastering Relays: From Basics to STM32 Control with Real Code

This tutorial explains relay fundamentals, classifications, electrical parameters, wiring diagrams, and provides a complete STM32‑based implementation with source code to control a relay and toggle an LED, offering practical guidance for embedded hardware projects.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Mastering Relays: From Basics to STM32 Control with Real Code

1. Introduction

Relays are ubiquitous electromechanical switches used in household appliances, industrial equipment, communication networks, transportation, and medical devices. They serve as an entry point for learning basic electronic principles and provide a solid foundation for more advanced topics.

2. Relay Overview

A relay functions like a switch: when its coil is energized, a small control current activates a larger load circuit. Compared with a simple mechanical switch, a relay offers higher reliability and flexibility for complex control tasks.

3. Working Principle

When voltage is applied to the coil, a magnetic field moves the armature, changing the contact state (normally open or normally closed). If the power source is removed, the spring returns the armature, opening the load circuit. The control circuit is electrically isolated from the load circuit, allowing safe switching of high‑voltage or high‑current loads.

4. Types and Ratings

Relays are commonly classified by control voltage (5 V, 12 V, 24 V) and by the number of poles (1, 2, 4, 8). Low‑voltage relays are used with microcontrollers, 12 V relays appear in automotive and home appliances, and 24 V units are typical in industrial automation.

5. Electrical Parameters

Voltage | Static Current | Max Current | Trigger Voltage | Trigger Current | Max Load
5 V     | 5 mA           | 190 mA      | 5 V             | 2‑4 mA          | AC 250 V/10 A, DC 30 V/10 A
12 V    | 5 mA           | 80 mA       | 12 V            | 2‑4 mA          | AC 250 V/10 A, DC 30 V/10 A
24 V    | 5 mA           | 50 mA       | 24 V            | 2‑4 mA          | AC 250 V/10 A, DC 30 V/10 A

6. Wiring Diagram

Input side: Connect the power supply (DC+/VCC) to the relay’s voltage rating, ground (DC‑/GND) to the supply negative, and the control pin (IN) to a microcontroller GPIO that can output high or low levels.

Relay Pin | Circuit Connection | Note
DC+/VCC  | Power positive      | Match relay voltage (5 V/12 V/24 V)
DC‑/GND  | Power negative      | 
IN       | MCU GPIO            | High level → coil energized (relay closes)

Output side: The common terminal (COM) must always be connected. Choose either NO (normally open) or NC (normally closed) depending on the desired default state.

Relay Pin | Circuit               | Note
NO       | Load circuit (choose) | Open when coil de‑energized, closes when energized
COM      | Common terminal        | Shared connection for NO/NC
NC       | Load circuit (choose) | Closed when coil de‑energized, opens when energized

7. Practical Implementation with STM32

7.1 Goal

Use an STM32F103C8T6 to drive a 5 V relay, making an LED toggle on and off every second.

7.2 Hardware List

STM32F103C8T6 development board

5 V single‑coil relay

RGB LED module (using the red channel)

Battery pack for power

ST‑LINK V2 programmer

7.3 Connection Overview

STM32‑relay connection diagram
STM32‑relay connection diagram

7.4 Source Code

#include "sys.h"
#include "usart.h"
#include "delay.h"

// Relay‑controlled LED pin definition
#define LED_CLK()       __HAL_RCC_GPIOB_CLK_ENABLE()
#define LED_GPIO        GPIOB
#define LED_PIN         GPIO_PIN_8

void led_init(void); // LED initialization prototype

int main(void)
{
    HAL_Init();
    sys_stm32_clock_init(RCC_PLL_MUL9); // 72 MHz system clock
    delay_init(72);
    led_init();
    while (1)
    {
        HAL_GPIO_WritePin(LED_GPIO, LED_PIN, GPIO_PIN_SET);   // Relay energised, LED on
        delay_ms(1000);
        HAL_GPIO_WritePin(LED_GPIO, LED_PIN, GPIO_PIN_RESET); // Relay released, LED off
        delay_ms(1000);
    }
}

/**
 * @brief Initialize LED‑related IO and enable its clock
 */
void led_init(void)
{
    GPIO_InitTypeDef gpio_initstruct;
    LED_CLK();
    gpio_initstruct.Pin   = LED_PIN;
    gpio_initstruct.Mode  = GPIO_MODE_OUTPUT_PP;
    gpio_initstruct.Pull  = GPIO_PULLUP;
    gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(LED_GPIO, &gpio_initstruct);
}

7.5 Result

The relay clicks (“啪嗒”) as it energizes and releases, causing the red LED to turn on for one second and off for the next, repeating indefinitely.

Relay LED toggle demonstration
Relay LED toggle demonstration

8. Conclusion

Relays are reliable, versatile components for controlling high‑power circuits in embedded systems. Understanding their classifications, electrical parameters, and proper wiring enables developers to integrate them confidently into projects ranging from simple home automation to complex industrial control.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

HardwareC programmingRelaySTM32
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.