Arduino relay scheme

Arduino и реле

Описание

Электромагнитное реле – универсальный способ коммутировать нагрузку. Универсальность в том, что реле имеет чисто механический контакт, то есть физически замыкает контакты. Это позволяет коммутировать нагрузку как переменного, так и постоянного тока в широком диапазоне напряжений: от 0 до сетевого, то есть 220 Вольт. По току производитель обещает 10 А, то есть можно коммутировать например 2 кВт обогреватель. Само реле напрямую к микроконтроллеру подключать нельзя, поэтому для управления силовая схема развязывается с логической, соответственно китайцы выпускают несколько типов модулей реле:

В наборе идёт красный модуль с настройкой логического уровня (жёлтый джампер-перемычка между буквами H и L). В центре – самый дешёвый модуль с минимальной обвязкой, высокого уровня. И справа – тоже неплохой модуль, но низкого уровня, что не всегда удобно использовать. Примечание: реле высокого уровня переключается при высоком сигнале на логический вход, а низкого – низком. Все модули реле имеют три пина на одном конце и три на другом:

Слева находятся пины питания и управления самого реле:

  • VCC (DC+, +) – питание
  • GND (DC-, -) – “земля”
  • IN (S) – логический управляющий сигнал

Справа находятся выходы самого реле, это одна контактная группа с переключением:

  • COM (Common) – общий контакт
  • NO (Normal Open) – нормально разомкнутый относительно COM контакт
  • NC (Normal Close) – нормально замкнутый относительно COM контакт

Работает это следующим образом: само реле (синяя коробочка на плате) питается от VCC и GND и подключается на питание схемы, так как реле потребляет около 60 мА при переключении. Но управляется реле логическим сигналом от микроконтроллера, который подаётся на пин IN. На выходе реле наблюдается следующая картина: у неактивного реле замкнуты контакты COM и NC. При активации реле контакт переключается и COM замыкается с NO.

Реле высокого уровня будет включаться и потреблять ток при подаче высокого сигнала (5, 3.3V), а низкого – при подаче низкого (GND, 0V). Чисто логически удобнее использовать реле высокого уровня: подали высокий сигнал – реле включилось. Мы кстати разбирали реле вот в этом уроке. И вот в этом:

Подключение

Примеры

Для активации реле достаточно подать высокий сигнал (для реле из набора) на логический вход. Для примера и проверки подойдёт и классический пример “мигания светодиодом”:

Источник

Working with Relay with Arduino

This will show you how to interface the Relay and the Arduino for the purpose of switching

Arduino UNO
× 1
Wires
× 1
Relay
× 1

A relay is an electromechanical switch used mainly for switching application either high voltage or low voltage switching, and they can be also used with microcontrollers like the Arduino for controlling high voltage devices

The aim of writing this is to serve as a guide while to interface the relay and the Arduino or the ESP 32

We’ll be using the Arduino , Relay Module , Wires , LED (green) and a 220-ohm resistor

The relay pinout is as follows;

On the Input side

Positive —- «5v or External 5v Power Supply»

Control/Signal pin —— «digital Write pins on the Arduino «

On the Output Side

Normally Closed —- «preferably Empty»

Normally Open —- «Negative Terminal of the Load «

We will use the schematic below to connect our various component

If you wanted to test the relay to make sure it’s working copy and run the Relay tester code file on my GitHub then remove the signal pin (that’s pin 8 on my end) and insert it back at quick intervals; Ensure you are hearing the clicking sounds of the relay; That shows your relay is functional.

Another side point, Often manufacturers might make mistakes in labelling the input pins; Most relay modules come with inbuilt LED indicators that displays when they’ve been powered ON, So try to power the positive and negative terminal of your relay then the last vacant pin is your control/signal pin.

To interface the relay, it’s best to use the negative side of the load and connect it to the relay » Normally Open » pin in » series «. Then the » common ground» of the relay is then connected to the ground line of your connection

When connecting your load to the relay output terminals it is better to keep it at the » Normally Open» pin, because that is where the relay is switching to, although keeping it at the normally closed will perform the same function

Things to note when working with your Relay

* The relay is not an ideal switch. meaning don’t use your relay for basic switching purpose like turning on/off LED. it will wear off the mechanical parts faster. this example was just for demonstration

* They are not good for fast switch application

* Relays are more suitable for high voltage application or relatively slow switching like controlling servos.

Thanks a lot for your time and if you have any feedback or want to reach me find me on Twitter @_carlos_dev, for any comments feel free to leave it below; Thanks

Источник

Ардуино: модуль реле

Мы уже знаем как управлять слабым светодиодом и даже мощным двигателем с помощью Ардуино. Но как быть, если мы задумаем управлять устройствами, подключенными к бытовой сети? Напомню, что даже небольшая настольная лампа питается от источника переменного тока с напряжением 220 Вольт. Обычный полевой транзистор, который мы использовали в схеме с двигателем уже не подойдет.

Чтобы управлять мощной нагрузкой да еще и с переменным током воспользуемся реле. Это такое электромеханическое устройство, которое механическим способом замыкает цепь нагрузки с помощью электромагнита. Посмотрим на внутренности:

Принцип действия реле следующий. Подаем напряжение на электромагнитную катушку. В катушке возникает поле, которое притягивает металлическую лапку. В свою очередь, лапка механически замыкает контакты нагрузки.

У реле есть два основных применения. Во-первых, мы можем подав всего 5 Вольт на катушку, замкнуть цепь очень мощной нагрузки. Например, реле, используемое в уроках для Ардуино, может включить свет в доме или отключить забытый утюг. Во-вторых, некоторые виды реле могут одновременно замкнуть и разомкнуть сразу несколько разных цепей с разным напряжением.

Подключение реле к Ардуино

На этом уроке мы будем работать не с отдельным реле, а с целым релейным модулем. Помимо самого реле, модуль содержит еще и оптоэлектронную развязку с транзистором, которые защищают выводы Ардуино от скачков напряжения на катушке.

У одинарного модуля реле есть всего три контакта. Подключим их по следующей схеме.

Реле GND VCC In
Ардуино Уно GND +5V 3

Кстати, вход реле является инвертированным. Это означает, что высокий уровень на контакте In выключит катушку реле, а низкий уровень — включит.

Принципиальная схема

Внешний вид макета

Программа для Ардуино

Напишем простую программу, которая будет включать лампу на 3 секунды, а затем гасить на 1 секунду.

Загружаем программу на Ардуино. Теперь подключаем питание к лампе и к реле. Наконец, подаем питание на контроллер.

Автоматический светильник или уличный фонарь

С помощью контроллера, реле и датчика света можно сделать несложный автоматический светильник. Контроллер будет зажигать лампу в момент, когда уровень света на датчике станет меньше заданного значения.

В качестве датчика используем готовый модуль на основе фоторезистора. Подключим все три устройства по следующей схеме.

Принципиальная схема

Внешний вид макета

Программа автоматического светильника

Аналоговый вывод датчика дает значения в диапазоне от 0 до 1023. Причем, 0 — для максимального уровня света и 1023 для полной темноты.

Сначала нам нужно определиться при каком уровне света включать лампу, а при каком выключать. В нашей лаборатории при свете дня датчик показывает значение L = 120, а ночью около L = 700. Будем включать реле при L > 600, и выключать при L

Ардуино: модуль реле : 8 комментариев

А какой резистор преобразует напряжение в 3 вольта?

Источник

Arduino — Relay

In a previous tutorial, we have learned how to turn on/off an LED. In this tutorial, we are going to learn how to turn on/off some kind of devices that use the high voltage power supply(such as a light bulb, fan, electromagnetic lock, linear actuator. ).

The common: Just like controlling LED, we use the Arduino’s output pin to turn on/off them.

Hardware Required

1 × Arduino UNO or Genuino UNO
1 × USB 2.0 cable type A/B
1 × Relay
1 × LED Strip
1 × 12V Power Adapter
1 × Breadboard
n × Jumper Wires

About Relay

A relay is a programmable electrical switch, which can be controlled by Arduino or any micro-controller. It is used to programmatically control on/off the devices, which use the high voltage and/or high current.

It is a bridge between Arduino and high voltage devices.

When you are making projects that are connected to mains voltage, you need to know what you are doing, otherwise, you may shock yourself. This is a serious topic, and we want you to be safe. If you’re NOT 100% sure what you are doing, do yourself a favor and don’t touch anything. Ask someone who knows!

Although some kinds of relays support both DC and AC devices, We highly recommend you to use a DC device (≤24V) for testing.

Relay Pinout

Relay has two groups of pins: input (low voltage) group and output (high voltage) group.

Источник

Guide for Relay Module with Arduino

This article shows how to control mains voltage with the Arduino using a relay module. We make a brief introduction to the relay module and build a simple project example with the Arduino. The example we’ll build shows how to control a relay module with an Arduino and a PIR motion sensor.

By the end of this tutorial, you should be able to control any electronics appliances with your Arduino using a relay module.

Introducing the Relay Module

A relay is an electrically operated switch that can be turned on or off, letting the current go through or not, and can be controlled with low voltages, like the 5V provided by the Arduino pins.

Controlling a relay module with the Arduino is as simple as controlling any other output as we’ll see later on.

This relay module has two channels (those blue cubes). There are other models with one, four and eight channels. This module should be powered with 5V, which is appropriate to use with an Arduino. There are other relay modules that are powered using 3.3V, which is ideal for ESP32, ESP8266, and other microcontrollers.

Get a relay module:

Relay Pinout

The following figure shows the relay module pinout.

The six pins on the left side of the relay module connect high voltage, and the pins on the right side connect the component that requires low voltage—the Arduino pins.

Mains voltage connections

The high-voltage side has two connectors, each with three sockets: common (COM), normally closed (NC), and normally open (NO).

  • COM: common pin
  • NC (Normally Closed): the normally closed configuration is used when you want the relay to be closed by default, meaning the current is flowing unless you send a signal from the Arduino to the relay module to open the circuit and stop the current.
  • NO (Normally Open): the normally open configuration works the other way around: the relay is always open, so the circuit is broken unless you send a signal from the Arduino to close the circuit.

If you just want to light up a lamp occasionally, it is better to use a normally-open circuit configuration.

Pin wiring

The low-voltage side has a set of four pins and a set of three pins.

The set at the right consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2) to control the bottom and top relays, respectively.

The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay.

Note: notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is blue, but yours may be a different color. The jumper cap allows you to choose whether the circuit is physically connected to the Arduino circuit or not, and you can choose to have it on or not. With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the Arduino’s power pin, so the relay module and the Arduino circuits are not physically isolated from each other (this is the configuration we’ll use). Without the jumper cap, you need to provide an independent power source to power up the relay’s electromagnet through the JD-VCC pin. That configuration physically isolates the relays from the Arduino with the module’s built-in optocoupler.

The connections between the relay module and the Arduino are really simple:

  • GND: goes to ground
  • IN1: controls the first relay (it will be connected to an Arduino digital pin)
  • IN2: controls the second relay (it should be connected to an Arduino digital pin if you are using this second relay. Otherwise, you don’t need to connect it)
  • VCC: goes to 5V

Example: Controlling a Lamp with a Relay Module and PIR Motion Sensor

In this example, we create a motion sensitive lamp. A lamp lights up for 10 seconds every time motion is detected.

Motion will be detected using a PIR motion sensor. If you are not familiar with the PIR motion sensor, you can read the following post:

To control the lamp with mains voltage we’ll use a relay module in normally-open configuration.

Safety warning

Before proceeding with this project, I want to let you know that you’re dealing with mains voltage. Please read the safety warning below carefully.

Warning: when you are making projects that are connected to mains voltage, you really need to know what you are doing, otherwise you may shock yourself. This is a serious topic, and we want you to be safe. If you’re not 100% sure what you are doing, do yourself a favor and don’t touch anything. Ask someone who knows!

Parts required

Here’s the needed parts for this example:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Copy the following code to your Arduino IDE and upload it to your Arduino board.

Warning: you shouldn’t upload new code while your Arduino is connected to the relay.

How the code works

First, we create variables to hold the pin the relay IN1 pin is connected to and to save the relay state:

The PIR motion sensor is connected to pin 2 :

We need to create some auxiliary variables to handle timers with the PIR motion sensor. The lastDebounceTime variable saves the last time motion was detected. The debounceDelay saves how much time the lamp should remain on after motion is detected (here we’re setting 10 seconds = 10000 milliseconds)

In the setup() , we set the relay as an OUTPUT and turn it off by default:

Because we’re using a normally open configuration, there is no contact between the COM and NO sockets unless you trigger the relay. The relay is triggered when the input goes below about 2 V. That means if you send a LOW signal from the Arduino, the relay turns on, and if you send a HIGH signal, the relay turns off; it works with inverted logic.

Set the PIR motion sensor as an interrupt:

Whenever the PIR motion sensor is triggered, it calls the detectMotion() function declared at the end of the code to turn the relay on:

In the loop() , we check whether 10 seconds have passed since the relay is on. If that condition is true, we can turn the relay off.

Schematic

Assemble all the parts as shown in the schematic diagram.

Warning: do not touch any wires that are connected to mains voltage. Also make sure you have tighten all screws of the relay module.

The lamp is connected to the relay using a normally open configuration. The Arduino controls the relay through pin 8 ( pin 8 is connected to the relay IN1 pin). Finally, the PIR motion sensor is connected to pin 2 .

Demonstration

After uploading the code and wiring the circuit, you can test your setup.

When motion is detected, your lamp lights up. If there isn’t motion for 10 seconds, the lamp turns off.

Wrapping Up

Controlling a relay module with the Arduino is as simple as controlling an output – you just need to send HIGH or LOW signals using an Arduino digital pin. With the relay module you can control almost any AC electronics appliances (not just lamps).

We hope you’ve found this guide useful. If you like this project, you may also like our premium Arduino course:

We have more than 60 free tutorials and projects with the Arduino. If you’re looking for a guide for a specific module, we probably have what you’re looking for.

Finally, you can also get access to our FREE resources here.

Источник

Adblock
detector