{"id":92436,"date":"2020-01-04T16:35:21","date_gmt":"2020-01-04T16:35:21","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=92436"},"modified":"2020-05-06T10:17:26","modified_gmt":"2020-05-06T10:17:26","slug":"micropython-relay-module-esp32-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/micropython-relay-module-esp32-esp8266\/","title":{"rendered":"MicroPython: Relay Module with ESP32\/ESP8266 (Guide + Web Server)"},"content":{"rendered":"\n<p>Using a relay with the ESP32 or ESP8266 is a great way to control AC household appliances remotely. This tutorial explains how to control a relay module with the ESP32 or ESP8266 using <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">MicroPython firmware<\/a>.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython Relay Module with ESP32 and ESP8266: Guide and Web Server\" class=\"wp-image-92447\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<p>We&#8217;ll take a look at how a relay module works, how to connect the relay to the ESP32 or ESP8266 boards and build a web server to control a relay remotely.<\/p>\n\n\n\n<p>We have similar guides using Arduino IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-relay-module-ac-web-server\/\"><strong>Guide for ESP32 Relay Module with Arduino IDE<\/strong> &#8211; Control AC Appliances + Web Server Example<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-relay-module-ac-web-server\/\"><strong>Guide for ESP8266 Relay Module with Arduino IDE<\/strong> &#8211; Control AC Appliances + Web Server Example<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Thonny IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Installing and getting started with Thonny IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py<\/a><\/li><\/ul><\/li><li>uPyCraft IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with uPyCraft IDE<\/a><\/li><li>Install uPyCraft IDE (<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-windows-pc-instructions\/\">Windows<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-mac-os-x-instructions\/\">Mac OS X<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-linux-ubuntu-instructions\/\">Linux<\/a>)<\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"rntbox rntclblue\">Learn more about MicroPython:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with ESP32 and ESP8266 eBook<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introducing Relays<\/h2>\n\n\n\n<p>A relay is an electrically operated switch and like any other switch, it that can be turned on or off, letting the current go through or not. It can be controlled with low voltages, like the 3.3V provided by the ESP32\/ESP8266 GPIOs and allows us to control high voltages like 12V, 24V or mains voltage (230V in Europe and 120V in the US).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1, 2, 4, 8, 16 Channels Relay Modules<\/h3>\n\n\n\n<p>There are different relay modules with a different number of channels. You can find relay modules with one, two, four, eight and even sixteen channels. The number of channels determines the number of outputs we&#8217;ll be able to control.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-1-2-4-8-ch-channel-modules.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Relay modules with different number of channels 1, 2, 4, 8, 16 Channels\" class=\"wp-image-91706\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-1-2-4-8-ch-channel-modules.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-1-2-4-8-ch-channel-modules.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>There are relay modules whose electromagnet can be powered by 5V and with 3.3V. Both can be used with the ESP32 or ESP8266 &#8211; you can either use the VIN pin (that provides 5V) or the 3.3V pin.<\/p>\n\n\n\n<p>Additionally, some come with built-in optocoupler that add an extra &#8220;layer&#8221; of protection, optically isolating the ESP boards from the relay circuit.<\/p>\n\n\n\n<p><strong>Get a relay module<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a rel=\"noreferrer noopener nofollow\" href=\"https:\/\/makeradvisor.com\/tools\/5v-2-channel-relay-module-optocoupler\/\" target=\"_blank\">5V 2-channel relay module<\/a> (with optocoupler)<\/li><li><a rel=\"noreferrer noopener nofollow\" href=\"https:\/\/www.banggood.com\/2Pcs-5V-1-Channel-Level-Trigger-Optocoupler-Relay-Module-For-Arduino-p-1366337.html?p=MA240439985285201910\" target=\"_blank\">5V 1-channel relay module<\/a> (with optocoupler) <\/li><li><a rel=\"noreferrer noopener nofollow\" href=\"https:\/\/www.banggood.com\/5V-8-Channel-Relay-Module-Board-For-Arduino-PIC-AVR-DSP-ARM-p-74110.html?p=MA240439985285201910\" target=\"_blank\">5V 8-channel relay module<\/a> (with optocoupler) <\/li><li><a href=\"https:\/\/www.banggood.com\/BESTEP-16-Channel-5V-Relay-Module-LM2596-With-Optocoupler-Protection-Low-Level-Trigger-For-Auduino-p-1390338.html?p=MA240439985285201910&amp;cur_warehouse=CN\" target=\"_blank\" rel=\"noreferrer noopener nofollow\" aria-label=\"5V 16-channel relay module (opens in a new tab)\">5V 16-channel relay module<\/a> (with optocoupler)<\/li><li><a rel=\"noreferrer noopener nofollow\" href=\"https:\/\/www.banggood.com\/BESTEP-1-Channel-3_3V-Low-Level-Trigger-Relay-Module-Optocoupler-Isolation-Terminal-For-Arduino-p-1355736.html?p=MA240439985285201910\" target=\"_blank\">3.3V 1-channel relay module<\/a> (with optocoupler) <\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Relay Pinout<\/h2>\n\n\n\n<p>For demonstration purposes, let&#8217;s take a look at the pinout of a 2-channel relay module. Using a relay module with a different number of channels is similar.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"850\" height=\"372\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/11\/Relay-pinout.png?resize=850%2C372&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"2-channel Relay Module Pinout\" class=\"wp-image-91429\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/11\/Relay-pinout.png?w=850&amp;quality=100&amp;strip=all&amp;ssl=1 850w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/11\/Relay-pinout.png?resize=300%2C131&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/11\/Relay-pinout.png?resize=768%2C336&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 850px) 100vw, 850px\" \/><\/figure><\/div>\n\n\n\n<p>On the left side, there are two sets of three sockets to connect high voltages, and the pins on the right side (low-voltage) connect to the ESP GPIOs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mains Voltage Connections<\/h3>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-output-pins-pinout.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Relay module mains voltage side\" class=\"wp-image-91707\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-output-pins-pinout.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-output-pins-pinout.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>The relay module shown in the previous photo has two connectors, each with three sockets: common (<span class=\"rnthl rntcblack\">COM<\/span>), Normally Closed (<span class=\"rnthl rntclblue\">NC<\/span>), and Normally Open (<span class=\"rnthl rntcyellow\">NO<\/span>).<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>COM:<\/strong>&nbsp;connect the current you want to control (mains voltage).<\/li><li><strong>NC&nbsp;(Normally Closed):<\/strong>&nbsp;the normally closed configuration is used when you want the relay to be closed by default. The NC are COM pins are connected, meaning the current is flowing unless you send a signal from the ESP to the relay module to open the circuit and stop the current flow.<\/li><li><strong>NO&nbsp;(Normally Open):<\/strong>&nbsp;the normally open configuration works the other way around: there is no connection between the NO and COM pins, so the circuit is broken unless you send a signal from the ESP to close the circuit.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Control Pins<\/h3>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-with-optocoupler-top-view.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"2-channel Relay Module\" class=\"wp-image-91711\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-with-optocoupler-top-view.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-with-optocoupler-top-view.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>The low-voltage side has a set of four pins and a set of three pins. The first set consists of <span class=\"rnthl rntcred\">VCC<\/span> and <span class=\"rnthl rntcblack\">GND<\/span> to power up the module, and input 1 (<span class=\"rnthl rntclblue\">IN1<\/span>) and input 2 (<span class=\"rnthl rntclgreen\">IN2<\/span>) to control the bottom and top relays, respectively. <\/p>\n\n\n\n<p>If your relay module only has one channel, you&#8217;ll have just one IN pin. If you have four channels, you&#8217;ll have four IN pins, and so on.<\/p>\n\n\n\n<p>The signal you send to the IN pins, determines whether the relay is active or not. The relay is triggered when the input goes below about 2V. This means that you&#8217;ll have the following scenarios:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Normally Closed configuration (NC)<\/strong>:<ul><li>HIGH signal &#8211; current is flowing<\/li><li>LOW signal &#8211; current is <strong>not <\/strong>flowing<\/li><\/ul><\/li><li><strong>Normally Open configuration (NO)<\/strong>:<ul><li>HIGH signal &#8211; current is <strong>not <\/strong>flowing<\/li><li>LOW signal &#8211; current in flowing<\/li><\/ul><\/li><\/ul>\n\n\n\n<p>You should use a normally closed configuration when the current should be flowing most of the times, and you only want to stop it occasionally. <\/p>\n\n\n\n<p>Use a normally open configuration when you want the current to flow occasionally (for example, turn on a lamp occasionally). <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Power Supply Selection<\/h3>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-input-pins-pinout.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"2-channel relay module control pins\" class=\"wp-image-91708\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-input-pins-pinout.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/Relay-2-ch-channel-module-input-pins-pinout.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>The second set of pins consists of <span class=\"rnthl rntcblack\">GND<\/span>, <span class=\"rnthl rntcred\">VCC<\/span>, and <span class=\"rnthl rntcorange\">JD-VCC<\/span> pins. The <span class=\"rnthl rntcorange\">JD-VCC<\/span> pin powers the electromagnet of the relay. Notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is yellow, but yours may be a different color.<\/p>\n\n\n\n<p>With the jumper cap on, the <span class=\"rnthl rntcred\">VCC<\/span> and <span class=\"rnthl rntcorange\">JD-VCC<\/span> pins are connected. That means the relay electromagnet is directly powered from the ESP power pin, so the relay module and the ESP circuits are not physically isolated from each other. <\/p>\n\n\n\n<p>Without the jumper cap, you need to provide an independent power source to power up the relay\u2019s electromagnet through the <span class=\"rnthl rntcorange\">JD-VCC<\/span> pin. That configuration physically isolates the relays from the ESP with the module\u2019s built-in optocoupler, which prevents damage to the ESP in case of electrical spikes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wiring a Relay Module to the ESP32\/ESP8266<\/h2>\n\n\n\n<p class=\"rntbox rntcred\"><strong>Warning: <\/strong> in this example, we\u2019re dealing with mains voltage. Misuse can result in serious injuries. If you&#8217;re not familiar with mains voltage ask someone who is to help you out. While programming the ESP or wiring your circuit make sure everything is disconnected from mains voltage.<\/p>\n\n\n\n<p>Alternatively, you can use a 12V power source to control 12V appliances.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">ESP32 Schematic Diagram<\/h3>\n\n\n\n<p>Connect the relay module to the ESP32 as shown in the following diagram. The diagram shows wiring for a 2-channel relay module, wiring a different number of channels is similar. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1038\" height=\"671\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?resize=1038%2C671&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Wiring a Relay Module to the ESP32 Schematic Circuit\" class=\"wp-image-91723\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?w=1038&amp;quality=100&amp;strip=all&amp;ssl=1 1038w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?resize=300%2C194&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?resize=1024%2C662&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp32-wiring.png?resize=768%2C496&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1038px) 100vw, 1038px\" \/><\/a><\/figure><\/div>\n\n\n\n<p>In this example, we&#8217;re controlling a lamp. We just want to light up the lamp occasionally, so it is better to use a normally open configuration.<\/p>\n\n\n\n<p class=\"rntbox rntclgreen\">We&#8217;re connecting the IN1 pin to <span class=\"rnthl rntclgreen\">GPIO 26<\/span>, you can use any other suitable GPIO. See <a href=\"https:\/\/randomnerdtutorials.com\/esp32-pinout-reference-gpios\/\">ESP32 GPIO Reference Guide<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">ESP8266 Schematic Diagram<\/h3>\n\n\n\n<p>Follow the next schematic diagram if you&#8217;re using an ESP8266.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1038\" height=\"661\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?resize=1038%2C661&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Wiring a Relay Module to the ESP8266 Schematic Circuit\" class=\"wp-image-91891\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?w=1038&amp;quality=100&amp;strip=all&amp;ssl=1 1038w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?resize=300%2C191&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?resize=1024%2C652&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/relay-esp8266-wiring.png?resize=768%2C489&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1038px) 100vw, 1038px\" \/><\/a><\/figure><\/div>\n\n\n\n<p class=\"rntbox rntclgreen\">We\u2019re connecting the IN1 pin to&nbsp;GPIO 5, you can use any other suitable GPIO. See&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-pinout-reference-gpios\/\">ESP8266 GPIO Reference Guide<\/a>. <\/p>\n\n\n\n<p class=\"rntbox rntclblue\">The best ESP8266 pins to use with relays are: GPIO 5, GPIO 4, GPIO 14, GPIO 12 and GPIO 13. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Controlling a Relay Module &#8211; MicroPython Code (Script)<\/h2>\n\n\n\n<p>The code to control a relay with the ESP32 or ESP8266 is as simple as controlling an LED or any other output. In this example, as we&#8217;re using a normally open configuration, we need to send a LOW signal to let the current flow, and a HIGH signal to stop the current flow.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/ESP32-Relay-Module-Tutorial-project-example-off.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Control a Lamp with the ESP32 or ESP8266 using a Relay Module\" class=\"wp-image-91717\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/ESP32-Relay-Module-Tutorial-project-example-off.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/12\/ESP32-Relay-Module-Tutorial-project-example-off.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>Copy the following code to the&nbsp;<em>main.py<\/em>&nbsp;file and upload it to your board. It lights up your lamp for 10 seconds and turn it off for another 10 seconds.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\n\nfrom machine import Pin\nfrom time import sleep\n\n# ESP32 GPIO 26\nrelay = Pin(26, Pin.OUT)\n\n# ESP8266 GPIO 5\n#relay = Pin(5, Pin.OUT)\n\nwhile True:\n  # RELAY ON\n  relay.value(0)\n  sleep(10)\n  # RELAY OFF\n  relay.value(1)\n  sleep(10)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_blink_relay.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the code works<\/h3>\n\n\n\n<p>Import the <span class=\"rnthl rntliteral\">Pin<\/span> class from the <span class=\"rnthl rntliteral\">machine<\/span> module to interact with the GPIOs. We also import the <span class=\"rnthl rntliteral\">sleep()<\/span> method from the <span class=\"rnthl rntliteral\">time<\/span> module to add delays.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import Pin\nfrom time import sleep<\/code><\/pre>\n\n\n\n<p>Then, we define a <span class=\"rnthl rntliteral\">Pin<\/span> object called <span class=\"rnthl rntliteral\">relay<\/span> on <span class=\"rnthl rntclgreen\">26<\/span> (if you&#8217;re using an ESP32) and define it as an output.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># ESP32 GPIO 26\nrelay = Pin(26, Pin.OUT)<\/code><\/pre>\n\n\n\n<p>In case you&#8217;re using an ESP8266, use <span class=\"rnthl rntclgreen\">GPIO 5<\/span> instead. Comment the previous line and uncomment the following.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># ESP8266 GPIO 5\n#relay = Pin(5, Pin.OUT)<\/code><\/pre>\n\n\n\n<p>In the while loop, send a LOW signal to light up the lamp for 10 seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># RELAY ON\nrelay.value(0)\nsleep(10)<\/code><\/pre>\n\n\n\n<p>If you&#8217;re using a normally closed configuration, send a HIGH signal to light up the lamp.<\/p>\n\n\n\n<p>Stop the current flow by sending a HIGH signal to the relay pin. If you&#8217;re using a normally closed configuration, send a LOW signal to stop the current flow.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># RELAY OFF\nrelay.value(1)\nsleep(10)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Control Relay Module with MicroPython Web Server<\/h2>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server.png?resize=338%2C435&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Control Relay with Web Server - MicroPython ESP32 and ESP8266\" class=\"wp-image-92445\" width=\"338\" height=\"435\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server.png?w=450&amp;quality=100&amp;strip=all&amp;ssl=1 450w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server.png?resize=233%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 233w\" sizes=\"(max-width: 338px) 100vw, 338px\" \/><\/figure><\/div>\n\n\n\n<p>In this section, we&#8217;ve created a web server example that allows you to control a relay remotely via web server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">boot.py<\/h3>\n\n\n\n<p>Copy the following code to your <em>boot.py<\/em> file.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\n\ntry:\n  import usocket as socket\nexcept:\n  import socket\n\nfrom machine import Pin\nimport network\n\nimport esp\nesp.osdebug(None)\n\nimport gc\ngc.collect()\n\nssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\n\nstation = network.WLAN(network.STA_IF)\n\nstation.active(True)\nstation.connect(ssid, password)\n\nwhile station.isconnected() == False:\n  pass\n\nprint('Connection successful')\nprint(station.ifconfig())\n\n# ESP32 GPIO 26\nrelay = Pin(26, Pin.OUT)\n\n# ESP8266 GPIO 5\n#relay = Pin(5, Pin.OUT)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_relay_web_server_boot.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Insert your network credentials in the following variables:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>ssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'<\/code><\/pre>\n\n\n\n<p>Uncomment one of the following lines accordingly to the board you&#8217;re using. By default, it&#8217;s set to use the ESP32 GPIO.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># ESP32 GPIO 26\nrelay = Pin(26, Pin.OUT)\n\n# ESP8266 GPIO 5\n#relay = Pin(5, Pin.OUT)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">main.py<\/h3>\n\n\n\n<p>Copy the following to your <em>main.py<\/em> file.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\n\ndef web_page():\n  if relay.value() == 1:\n    relay_state = ''\n  else:\n    relay_state = 'checked'\n  html = &quot;&quot;&quot;&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;&lt;style&gt;\n  body{font-family:Arial; text-align: center; margin: 0px auto; padding-top:30px;}\n  .switch{position:relative;display:inline-block;width:120px;height:68px}.switch input{display:none}\n  .slider{position:absolute;top:0;left:0;right:0;bottom:0;background-color:#ccc;border-radius:34px}\n  .slider:before{position:absolute;content:&quot;&quot;;height:52px;width:52px;left:8px;bottom:8px;background-color:#fff;-webkit-transition:.4s;transition:.4s;border-radius:68px}\n  input:checked+.slider{background-color:#2196F3}\n  input:checked+.slider:before{-webkit-transform:translateX(52px);-ms-transform:translateX(52px);transform:translateX(52px)}\n  &lt;\/style&gt;&lt;script&gt;function toggleCheckbox(element) { var xhr = new XMLHttpRequest(); if(element.checked){ xhr.open(&quot;GET&quot;, &quot;\/?relay=on&quot;, true); }\n  else { xhr.open(&quot;GET&quot;, &quot;\/?relay=off&quot;, true); } xhr.send(); }&lt;\/script&gt;&lt;\/head&gt;&lt;body&gt;\n  &lt;h1&gt;ESP Relay Web Server&lt;\/h1&gt;&lt;label class=&quot;switch&quot;&gt;&lt;input type=&quot;checkbox&quot; onchange=&quot;toggleCheckbox(this)&quot; %s&gt;&lt;span class=&quot;slider&quot;&gt;\n  &lt;\/span&gt;&lt;\/label&gt;&lt;\/body&gt;&lt;\/html&gt;&quot;&quot;&quot; % (relay_state)\n  return html\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 80))\ns.listen(5)\n\nwhile True:\n  try:\n    if gc.mem_free() &lt; 102000:\n      gc.collect()\n    conn, addr = s.accept()\n    conn.settimeout(3.0)\n    print('Got a connection from %s' % str(addr))\n    request = conn.recv(1024)\n    conn.settimeout(None)\n    request = str(request)\n    print('Content = %s' % request)\n    relay_on = request.find('\/?relay=on')\n    relay_off = request.find('\/?relay=off')\n    if relay_on == 6:\n      print('RELAY ON')\n      relay.value(0)\n    if relay_off == 6:\n      print('RELAY OFF')\n      relay.value(1)\n    response = web_page()\n    conn.send('HTTP\/1.1 200 OK\\n')\n    conn.send('Content-Type: text\/html\\n')\n    conn.send('Connection: close\\n\\n')\n    conn.sendall(response)\n    conn.close()\n  except OSError as e:\n    conn.close()\n    print('Connection closed')\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_relay_web_server_main.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>We won&#8217;t explain how this code works because we already have a very similar tutorial with detailed explanation of each line of code. Read the next project:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-micropython-web-server\/\">ESP32\/ESP8266 MicroPython Web Server \u2013 Control Outputs<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>After making the necessary changes, upload the <em>boot.py<\/em> and <em>main.py<\/em> files to your board. Press the EN\/RST button and in the Shell you should get the ESP IP address.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"701\" height=\"175\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/esp32-esp8266-relay-web-server-ip-address.png?resize=701%2C175&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 ESP8266 Relay Web Server IP Address\" class=\"wp-image-92459\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/esp32-esp8266-relay-web-server-ip-address.png?w=701&amp;quality=100&amp;strip=all&amp;ssl=1 701w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/esp32-esp8266-relay-web-server-ip-address.png?resize=300%2C75&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 701px) 100vw, 701px\" \/><\/figure><\/div>\n\n\n\n<p>Then, open a browser in your local network and type the ESP IP address to get access to the web server.<\/p>\n\n\n\n<p>You should get a web page with a toggle button that allows you to control your relay remotely using your smartphone or your computer.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server-ac-device.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Control a relay with web server using ESP32 or ESP8266 using MicroPython firmware\" class=\"wp-image-92446\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server-ac-device.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-ESP32-ESP8266-control-relay-web-server-ac-device.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Enclosure for Safety<\/h3>\n\n\n\n<p>For a final project, make sure you place your relay module and ESP inside an enclosure to avoid any AC pins exposed.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/enclosure-for-relay-module.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Plastic Enclosure for Safety and hide exposed AC pins of the relay module\" class=\"wp-image-92448\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/enclosure-for-relay-module.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/enclosure-for-relay-module.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial you&#8217;ve learned how to control relays with the ESP32 or ESP8266 using MicroPython. We have similar guides using Arduino IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-relay-module-ac-web-server\/\">[Arduino IDE] Guide to control a Relay Module with the <strong>ESP32<\/strong><\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-relay-module-ac-web-server\/\">[Arduino IDE] Guide to control a Relay Module with <strong>ESP8266<\/strong><\/a><\/li><\/ul>\n\n\n\n<p>Controlling a relay with the ESP32 or ESP8266 is as easy controlling any other output, you just need to send HIGH and LOW signals as you would do to control an LED.<\/p>\n\n\n\n<p>You can use our web server examples that control outputs to control relays. You just need to pay attention to the configuration you&#8217;re using. In case you&#8217;re using a normally open configuration, the relay works with inverted logic. You can use the following web server examples to control your relay:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-web-server-arduino-ide\/\">ESP32 Web Server \u2013 Arduino IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-web-server-spiffs-spi-flash-file-system\/\">ESP32 Web Server using SPIFFS (control outputs)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-micropython-web-server\/\">ESP32\/ESP8266 MicroPython Web Server \u2013 Control Outputs<\/a><\/li><\/ul>\n\n\n\n<p>Learn more about MicroPython with the ESP32 and ESP8266 with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with the ESP32 and ESP8266 (eBook)<\/a> <\/strong><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32-esp8266-micropython\/\">More MicroPython Projects and Tutorials&#8230;<\/a><\/li><\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Using a relay with the ESP32 or ESP8266 is a great way to control AC household appliances remotely. This tutorial explains how to control a relay module with the ESP32 &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"MicroPython: Relay Module with ESP32\/ESP8266 (Guide + Web Server)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/micropython-relay-module-esp32-esp8266\/#more-92436\" aria-label=\"Read more about MicroPython: Relay Module with ESP32\/ESP8266 (Guide + Web Server)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":92447,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[281,276,214,265,240,309,264,218],"tags":[],"class_list":["post-92436","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32-project","category-esp32","category-esp8266","category-esp8266-project","category-esp8266-projects","category-0-esp32-micropython","category-project","category-web-server"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/01\/MicroPython-firmware-ESP32-ESP8266-control-relay-web-server-ac-voltage.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/92436","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=92436"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/92436\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/92447"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=92436"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=92436"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=92436"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}