---
title: "Remote Triggering of Relays with HTML"
url: "https://maker.wiznet.io/praveen_k/projects/Remote-Triggering-of-Relays-with-HTML/"
markdown_url: "https://maker.wiznet.io/praveen_k/projects/Remote-Triggering-of-Relays-with-HTML/md"
type: "UCC: User Created Content"
author: "praveen_k"
original_author: "praveen_k"
original_url: "https://portal.vidadesilicio.com.br/shield-ethernet-w5100-acionamento-remoto-de-reles-com-html/"
published: "2021-07-08"
language: "en"
hardware: ["WIZnet W5100 ethernet shield", "Arduino uno rev3", "Relay module"]
likes: 0
views: 235
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# Remote Triggering of Relays with HTML

> Remote Triggering of Relays with HTML

Original author: praveen_k (source: https://portal.vidadesilicio.com.br/shield-ethernet-w5100-acionamento-remoto-de-reles-com-html/)

## Components

- **WIZnet W5100 ethernet shield** x 1 ([docs](https://www.wiznet.hk/en/open-source-hardware/102-w5100s-ethernetshield.html?search_query=W5100+ethernet+shield&results=84))
- **Arduino uno rev3** x 1
- **Relay module** x 1
- Software: **Arduino IDE** ([docs](https://www.arduino.cc/en/software))

## Article

In this tutorial you will learn how to create an application in which you will be able to create an interface, which in turn, will be presented in your internet browser, so that you can trigger relays. It is important, for the full understanding of this tutorial, that the reader has read all the previous tutorials:

- [Shield Ethernet W5100 ? Creating a Web Server with Arduino](https://wp.me/p97rit-eXG)

- [Shield Ethernet W5100 ? Monitoring Sensors with a Web Server](https://wp.me/p97rit-eXK)

- [Shield Ethernet W5100 ? Controlling Outputs via Web Server](https://portal.vidadesilicio.com.br/shield-ethernet-w5100-controlando-saidas-servidor-web-2/)

Index?[?[View](https://portal.vidadesilicio.com.br/shield-ethernet-w5100-acionamento-remoto-de-reles-com-html/#)?]

---

## Let's go - Developing the remote relay actuation system with HTML

### Required components

- [1 x Arduino Board UNO Rev 3](http://www.vidadesilicio.com.br/placa-uno-rev3-arduino.html)

- [1 x Shield Ethernet Wiznet W5100](http://www.vidadesilicio.com.br/shield-ethernet-wiznet-w5100.html)

- [1 x 4-channel Relay Module](https://www.vidadesilicio.com.br/modulo-rele-4-canais.html)

### assembling the project

![Shield Ethernet W5100 - HTML Remote Relay Trigger System](https://i2.wp.com/portal.vidadesilicio.com.br/wp-content/uploads/2018/01/rele_html.png?resize=781%2C538&ssl=1)

*Hardware Used.*

### programming

#include &lt;SPI.h>

#include &lt;Ethernet.h>

mac byte [] = { 0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED } ;

IPAddress ip ( 192, 168, 25, 16 ) ;

EthernetServer server ( 80 ) ;

void setup ()

{

Ethernet. begin ( mac, ip ) ;

server. begin () ;

pinMode ( 2,OUTPUT ) ;

pinMode ( 3,OUTPUT ) ;

pinMode ( 4,OUTPUT ) ;

pinMode ( 5,OUTPUT ) ;

digitalWrite ( 2,HIGH ) ;

digitalWrite ( 3,HIGH ) ;

digitalWrite ( 4,HIGH ) ;

digitalWrite ( 5,HIGH ) ;

}

void loop ()

{

String req_str;

EthernetClient client = server. available () ;

if ( client )

{

req_str = "" ;

boolean currentLineIsBlank = true ;

while ( client. Connected ())

{

if ( client. available ())

{

char c = client. read () ;

req_str += c;

if ( c == 'n' && currentLineIsBlank )

{

unsigned int start_position = req_str. indexOf ( "GET" ) + 4;

unsigned int end_position = req_str. indexOf ( "HTTP/" ) - 1;

String parameter = req_str. substring ( start_position,end_position ) ;

if ( parameter != "/favicon.ico" )

{

client. println ( "HTTP/1.1 200 OK" ) ;

client. println ( "Content-Type: text/html" ) ;

client. println ( "Connection: close" ) ;

client. println () ;

client. println ( "&lt;!DOCTYPE html>" ) ;

client. println ( "&lt;html lang="en">" ) ;

client. println ( "&lt;head>" ) ;

client. println ( "&lt;meta charset= "UTF-8"/>" ) ;

client. println ( "&lt;title>Triggering relays&lt;/title>" ) ;

client. println ( "&lt;/head>" ) ;

client. println ( "&lt;body>" ) ;

client. println ( "&lt;h1>Relay drive system V.1&lt;/h1>" ) ;

client. println ( "&lt;hr/>" ) ;

client. println ( "&lt;h2>Digital ports&lt;/h2>" ) ;

// client.println("&lt;p>Port D2:&lt;/p>");

client. println ( "&lt;form method="get">" ) ;

createform ( client, parameter ) ;

client. println ( "&lt;/form>" ) ;

client. println ( "&lt;/body>" ) ;

client. println ( "&lt;/html>" ) ;

}

break ;

}

if ( c == 'n' )

{

currentLineIsBlank = true ;

}

else if ( c != 'r' )

{

currentLineIsBlank = false ;

}

}

}

delay ( 1 ) ;

client. stop () ;

}

}

void createform ( EthernetClient client_aux, String parameter_aux )

{

for ( int i = 0; i &lt; 2; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>PIN NOT USED (DISABLED )&lt;/br>" ) ;

}

for ( int i = 2; i &lt; 6; i++ )

{

client_aux. println ( " D port " + String ( i ) + " ( Relay " + String ( i - 1 ) + " ) : " ) ;

if ( aux_parameter. indexOf ( "D" + String ( i ) + "=1" ) > -1 )

{

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" checked> ON&lt;/br> " ) ;

digitalWrite ( i,LOW ) ;

}

else

{

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()"> OFF&lt;/br>" ) ;

digitalWrite ( i,HIGH ) ;

}

}

for ( int i = 6; i &lt; 10; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>PIN NOT USED (DISABLED )&lt;/br>" ) ;

}

for ( int i = 10; i &lt; 14; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>IN USE BY ETHERNET SHIELD W5100 (DISABLED)&lt;/br>" ) ;

}

}

### putting it to work

![Shield Ethernet W5100 - HTML Remote Relay Trigger System](https://i0.wp.com/portal.vidadesilicio.com.br/wp-content/uploads/2018/01/sistema.png?resize=583%2C545&ssl=1)

*Relay drive system with HTML*

---

## understanding in depth

### software

Before we start with the explanation of the code, we would like to emphasize that we will only present the details of the topics not covered in the previous tutorials, as this way it will be easier to focus on the parts referring to the updates made to the already existing program, therefore, if If you have any questions about any part of the program that is not explained at this time, we suggest that you access our aforementioned materials.

#### **? Defining the prerequisites for the code to work**

Initially, we must include two libraries in the code so that it could work correctly.?The?**SPI.h**?library??**,**??responsible for the communication of the shield modules with the?**?Arduino UNO**??using the?**SPI?**?protocol??and the?**Ethernet.h?**?library??**,**??which acts by enabling the connection of the set, at first, with a local network. After including the mentioned libraries, we must define a??**MAC address**??(remember that this can be anything, as long as it is unique in your local network) and an??**IP address**??(this must be a valid and available address within your local network ).?In addition, we must create the object that will be responsible for representing the??**Web Server**??in the code (here, we call this??**server**?) and relate it to port 80.

#include &lt;SPI.h>

#include &lt;Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

IPAddress ip(192, 168, 25, 16);

EthernetServer server(80);

#### **? Definindo as configuracoes iniciais**

Dentro da funcao?**setup()**, devemos determinar o modo de operacao dos pinos digitais que serao utilizados (estes terao o papel de saidas digitais) . Alem disso,?iniciamos a conexao com a rede local atraves da funcao?**Ethernet.begin()?**(passando como parametro os enderecos?**MAC**?e?**IP**?definidos anteriormente) e tambem iniciamos o?**Servidor Web?**por meio da sentenca?**server.begin()?**(lembre-se que?**server**?e o objeto criado para representar o?**Servidor Web**?no codigo).

void setup()

{

Ethernet.begin(mac, ip);

server.begin();

pinMode(2,OUTPUT);

pinMode(3,OUTPUT);

pinMode(4,OUTPUT);

pinMode(5,OUTPUT);

digitalWrite(2,HIGH);

digitalWrite(3,HIGH);

digitalWrite(4,HIGH);

digitalWrite(5,HIGH);

}

Observe que alem da execucao dos procedimentos apresentados anteriormente, nos tambem optamos por colocar os pinos citados nivel alto, pois, os reles do modulo que utilizamos sao acionados com nivel baixo em suas entradas, portanto, como queremos que eles comecem sem qualquer tipo de acionamento, devemos proporcionar 5 volts em seus respectivos pinos de entrada.

#### **? Entendendo as requisicoes do navegador**

Nos tutoriais anteriores, ressaltamos o mecanismo basico de funcionamento dos codigos voltados para a criacao de Servidores Web, o qual, comeca atraves de um procedimento padrao, que por sua vez, consiste em utilizar uma variavel para obter caractere por caractere da requisicao feita pelo navegador ate que esta seja completamente recebida pelo?**Arduino UNO**, de modo que, apenas a partir deste ponto inicia-se o processo de elaboracao da pagina. Em nosso ultimo tutorial, apresentamos o modo de funcionamento do metodo GET, portanto, vamos utiliza-lo novamente no envio de informacoes provenientes dos formularios para o nosso Servidor Web. Entretanto, vamos seguir um caminho um pouco diferente para que voce possa ver a existencia de outras possibilidades. O primeiro passo neste procedimento sera a declaracao de uma variavel local, do tipo String (esta servira para armazenar a requisicao feita pelo navegador).

void loop()

{

String req_str;

.

.

.

Em seguida, criamos o processo no qual esta variavel sera preenchida com os caracteres da requisicao.

if (client.available())

{

char c = client.read();

req_str += c;

.

.

.

Por fim, declaramos duas variaveis do tipo inteiro sem sinal e uma do tipo String, as quais, serao responsaveis por retirar o que nos chamamos em nosso tutorial anterior de?**parametro da requisicao**. Alem disso, este trecho de codigo tambem cumpre o papel de determinar se o parametro e o texto?**/favicon.ico**, de modo que, caso nao seja (pois neste momento isto nao e interessante para nos), seguimos adiante na construcao da pagina. A explicacao das funcoes que compoem este passo estao demonstradas em nosso tutorial anterior. Voce pode acessa-lo clicando?[aqui](https://portal.vidadesilicio.com.br/shield-ethernet-w5100-controlando-saidas-servidor-web-2/)!

if(c == 'n' && currentLineIsBlank)

{

unsigned int posicao_inicial = req_str.indexOf("GET") + 4;

unsigned int posicao_final = req_str.indexOf("HTTP/") - 1;

String parametro = req_str.substring(posicao_inicial,posicao_final);

if(parametro != "/favicon.ico")

{

.

.

.

#### **? Enviando o cabecalho da pagina**

Apos termos detectado que o?**parametro da requisicao**?nao e o fragmento de texto?**/favicon.ico**, devemos primeiramente enviar o cabecalho padrao para o navegador.

client.println("HTTP/1.1 200 OK");

client.println("Content-Type: text/html");

client.println("Connection: close");

client.println();

#### **? Desenvolvendo a nossa pagina**

Para comecar a desenvolver a nossa pagina, utilizamos primeiro a sentenca?**&lt;!DOCTYPE html>**?para informarmos ao navegador que estamos utilizando a versao 5 da linguagem HTML.

client. println ( "&lt;!DOCTYPE html>" ) ;

As we know, between the?**&lt;head>**?and?**&lt;/head>**?tags?, we make some settings relevant to the functioning of the page we are developing.?The aforementioned settings correspond to the determination of the character set that should be used by the browser (to display accented characters) and the inclusion of a title in the browser's page tab.

client. println ( "&lt;head>" ) ;

client. println ( "&lt;meta charset= "UTF-8"/>" ) ;

client. println ( "&lt;title>Triggering relays&lt;/title>" ) ;

client. println ( "&lt;/head>" ) ;

In the body of the page, we start by writing some titles using the?**&lt;h1>?**?and &lt;?**h2**?>?header tags??.

client. println ( "&lt;body>" ) ;

client. println ( "&lt;h1>Relay drive system V.1&lt;/h1>" ) ;

client. println ( "&lt;hr/>" ) ;

client. println ( "&lt;h2>Digital ports&lt;/h2>" ) ;

.

.

.

Then, we add the form and explain that the method that will be used to send data in the request made by the browser will be GET.?Between the?**&lt;form>**?and?**&lt;/form>**?tags?, we create a function called?**criaformulario()**?, which will be responsible for creating the command interface in the browser page.

client. println ( "&lt;form method="get">" ) ;

createform ( client, parameter ) ;

client. println ( "&lt;/form>" ) ;

Finally, see the code responsible for creating the command interface, in full.

client.println("&lt;!DOCTYPE html>");

client.println("&lt;html lang="pt-br">");

client.println("&lt;head>");

client.println("&lt;meta charset= "UTF-8"/>");

client.println("&lt;title>Acionamento de reles&lt;/title>");

client.println("&lt;/head>");

client.println("&lt;body>");

client.println("&lt;h1>Sistema de acionamento de reles V.1&lt;/h1>");

client.println("&lt;hr/>");

client.println("&lt;h2>Portas digitais&lt;/h2>");

client.println ("&lt;form method="get">");

criarformulario (client, parametro);

client.println ("&lt;/form>");

client.println ("&lt;/body>");

client.println ("&lt;/html>");

#### **? Form creation function**

As we said before, the function?**criaformulario()**?will be responsible for creating the command interface that we will use.?This function is divided into three blocks, so that the first of them is responsible for creating the checkboxes referring to digital ports 0 and 1. Note that in the instruction for creating the checkboxes (whose operation has already been presented in our tutorials) there is the word?**disabled**?, which will make the checkbox not clickable (precisely because we are not using these pins).

for ( int i = 0; i &lt; 2; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>PIN NOT USED (DISABLED )&lt;/br>" ) ;

}

The second block concerns the creation of checkboxes for activating the 4 relays in the module used.?Note that the structure used is the same as the previous one, however, we use the?**indexOf()?**?function?to find out if there is any element of type “?**/?D_=1**?“?**?**(request parameter when any checkbox is selected).?If so, the checkbox is created and marked, if not, it is just created, but without being selected.?Consequently, we also activate the relay (with logic level 0) or not (with logic level 1), through the?**digitalWrite()**?function?.

for ( int i = 2; i &lt; 6; i++ )

{

client_aux. println ( " D port " + String ( i ) + " ( Relay " + String ( i - 1 ) + " ) : " ) ;

if ( aux_parameter. indexOf ( "D" + String ( i ) + "=1" ) > -1 )

{

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" checked> ON&lt;/br> " ) ;

digitalWrite ( i,LOW ) ;

}

else

{

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()"> OFF&lt;/br>" ) ;

digitalWrite ( i,HIGH ) ;

}

}

The third and fourth blocks are similar to the first, however, in the fourth for repeating structure, we just changed the text to signal that pins 10 to 13 are being used by the Shield Ethernet W5100.

for ( int i = 6; i &lt; 10; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>PIN NOT USED (DISABLED )&lt;/br>" ) ;

}

for ( int i = 10; i &lt; 14; i++ )

{

client_aux. println ( "Port D" + String ( i ) + ":" ) ;

client_aux. println ( "&lt;input type="checkbox" name="D" + String ( i ) + "" value="1" onclick="submit()" disabled>IN USE BY ETHERNET SHIELD W5100 (DISABLED)&lt;/br>" ) ;

}

}

---

## Final considerations

In this tutorial, we demonstrate how you can go about creating a relay drive system to be used?**?**through a web browser.?For this, we use an??**Arduino UNO**??together with an??**Ethernet Shield W5100.**

---

Source: https://maker.wiznet.io/praveen_k/projects/Remote-Triggering-of-Relays-with-HTML/
