Automation With ESP8266 and Solid State Relay

Introduction: Automation With ESP8266 and Solid State Relay

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects. New tutorials on Tuesdays and Fridays.

Today, we’ll discuss a component that isn’t necessarily well-known. However, it’s indispensable for those who enjoy industrial, commercial, or residential automation. This essential component is called the solid state relay. Solid state relays (SSR) are basically electronic devices used to switch resistive or inductive loads with numerous advantages over conventional electromechanical relays. In short, today we’ll provide a fast and flexible option for load control and extend the applications of electromechanical relays to SSRs.

Step 1: My Another Project "Automation With ESP8266 Using Relays"

This project is a version similar to the one I presented in the video, "Automation with ESP8266 using relays". But here, I've expanded the number of relays from two to eight. And today, I’ll once again discuss the ESP8266, because (let's face it) it has no competitor. This is due to its performance in relation to its price. It's very cheap considering its capabilities.

Step 2: Resources Used

• ESP8266 Devkit1.0

• 8 channel SSR module

• Jumpers for connection

• WiFi network available

• 5V power supply

• 127V bulb

• Lamp socket

• Parallel wire

Step 3: Demonstration

In this video, you’ll see a demonstration of the running circuit. In our assembly, we have solid state relays. The eighth relay is connected to a lamp at 127 volts. The other seven relays are with LED indicators. We also have the ESP8266, which has outputs connected directly to the relay modules.

Step 4: Sainsmart 8 Channel SSR Module

• Port Activation:

Low state: 0V to 0.5V

The indeterminate state: 0.5V to 2.5V

o High state: 2.5V to 20V

o Power supply 5V

• Load on each channel:

o Voltage: 75 to 264VAC (50 / 60Hz)

o Current: 0.1 to 2A

Step 5: Main Component - Solid State Relay (SSR)

Some advantages:

• They have no mechanical parts, increasing the service life.

• They respond better to higher frequency switching.

• They have zero crossing detection, and connect or disconnect loads at the zero voltage point of the sine wave, which reduces electromagnetic interference.

• They are smaller, quieter, and more resistant to mechanical vibrations.

• They feature greater compatibility with digital circuits and low drive currents.

Step 6: Traditional Relay and Solid State Relay

My friends, it’s important to mention that sometimes it’s better to use the traditional relay, and other situations where solid state relays are preferable. Thus, it is important to always analyze the advantages and disadvantages, which I’ll discuss now.

Some disadvantages

• They must have a correct design for heat dissipation.

• They are more sensitive to electrical surges and may require the use of varistors as a form of protection.

• I recommend using serial fast fuses with SSRs because, in the event of a short and possible damage, the SSRs tend to remain closed while keeping the load energized.

Step 7: Solid State Relay Diagram

Here is a diagram of what's inside the solid-state relay.

Step 8: Pines of Esp8266

Step 9: Circuit

Check the connection table.

Step 10: See Here the Details of Our Assembly.

Step 11: Source Code - Includes, Defines, and Webserver

As mentioned, in the video "Automation with ESP8266 using relays", I increased from two to eight relays. Here, we follow the same procedure. We included the ESP8266 WiFi library, defined the representation of the pins used for each of the relays, and created a server on port 80.

#include //Inclui biblioteca Wifi do ESP8266
//Define representação dos pinos usados para cada relé #define Rele_01 16 //mesmo que D0 #define Rele_02 5 //mesmo que D1 #define Rele_03 4 //mesmo que D2 #define Rele_04 0 //mesmo que D3 #define Rele_05 2 //mesmo que D4 #define Rele_06 14 //mesmo que D5 #define Rele_07 12 //mesmo que D6 #define Rele_08 13 //mesmo que D7 //Cria um server na porta 80 //(porta padrão para onde os navegadores enviam as requisições http) WiFiServer server(80);

Step 12: Source Code - Setup () - Serial and Pin Adjustment

Initialize the server we created on port 80, and show the serial monitor of the IP that the ESP has to verify to see if it is the same one that we configured.

void setup()
{ //Inicializa a Serial apenas para efeito de log Serial.begin(115200); //Ajusta o modo de todos os pinos pinMode(Rele_01, OUTPUT); pinMode(Rele_02, OUTPUT); pinMode(Rele_03, OUTPUT); pinMode(Rele_04, OUTPUT); pinMode(Rele_05, OUTPUT); pinMode(Rele_06, OUTPUT); pinMode(Rele_07, OUTPUT); pinMode(Rele_08, OUTPUT); //Ajusta o estado de todos os pinos digitalWrite(Rele_01, LOW); digitalWrite(Rele_02, LOW); digitalWrite(Rele_03, LOW); digitalWrite(Rele_04, LOW); digitalWrite(Rele_05, LOW); digitalWrite(Rele_06, LOW); digitalWrite(Rele_07, LOW); digitalWrite(Rele_08, LOW);

Step 13: Source Code - Setup () - Connecting to WiFi and Setting Address

In this step, we inform the current state of the ESP, which will connect the WiFi network available at the place of use. “New status” will then be shown on the serial monitor. We configure the fixed IP according to the network and send the configurations.

Serial.print("Conectando");//informando estado atual (debug)
//Faz o ESP se conectar à rede WiFi disponível no local de uso. //No nosso exemplo o ssid da rede é redeWiFi e a senha é senhateste WiFi.begin("redeWiFi", "senhateste"); //Enquanto o ESP não se conectar à rede while (WiFi.status() != WL_CONNECTED) { //Esperamos 100 milisegundos delay(100); Serial.print("."); } //Se chegou aqui é porque conectou à rede, //então mostramos no monitor serial para termos um feedback Serial.println(""); Serial.println("Conectou"); //Configurações do IP fixo. Você pode alterar conforme a sua rede IPAddress ip(192, 168, 43, 205); IPAddress gateway(192, 168, 43, 1); IPAddress subnet(255, 255, 255, 0); Serial.print("Configurando IP fixo para : "); Serial.println(ip); //Envia a configuração WiFi.config(ip, gateway, subnet);

Step 14: Source Code - Setup () - Starting the Server

Initialize the server we created on port 80, and show the serial monitor of the IP that the ESP has to verify to see if it is the same one that we configured.

//Inicializa o server que criamos na porta 80
server.begin(); //Mostramos no monitor serial o IP que o ESP possui //para verificarmos se é o mesmo que configuramos Serial.print("Server em: "); Serial.println(WiFi.localIP()); }

Step 15: Source Code - Loop () - Waiting for Connection

At this stage of the Loop, we check if any clients are trying to connect. If not, we can return.

void loop()
{ //Verifica se algum cliente está tentando se conectar WiFiClient client = server.available(); if (!client) { //Se não houver nenhum cliente podemos retornar pois não há nada a fazer return; }

Step 16: Source Code - Loop () - Client Connected, Getting Requisition

Here, we read the request.

<p>Serial.println("Novo cliente conectou");<br> 
//Fazemos a leitura da requisição
String req = client.readStringUntil('\r');
Serial.print("Requisição: ");

Step 17: Source Code - Mounting the HTML That Will Be Sent

I show here the html that we will return to the client, which is formed by two buttons (ON and OFF) for each relay. We’ll make the action link to each button to reach the ESP, so that it checks what action to take.

//Este é o html que iremos retornar para o cliente
//É composto basicamente de dois botões (ON e OFF) para cada relé //A parte que nos interessa é o LESSTHAN a href=' com a ação vinculada a cada botão //Quando clicamos em um destes botões essa informação chegará até o ESP para //que ele verifique qual ação deve executar //A parte dentro de 'LESSTHAN style>' é apenas para modificarmos o visual da página //que será exibida, você pode alterá-la como queira String html = "<html>" "<head>"

"<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'/>"

"<title>Controle Esp8266</title>"


"body{" "text-align: center;" "font-family: sans-serif;" "font-size:25px;" "padding: 25px;" "}" "p{" "color:#444;" "}" "button{" "outline: none;" "border: 2px solid #1fa3ec;" "border-radius:18px;" "background-color:#FFF;" "color: #1fa3ec;" "padding: 5px 25px;" "}" "button:active{" "color: #fff;" "background-color:#1fa3ec;" "}" "button:hover{" "border-color:#0000ff;" "}" "</style>" "</head>" "<body>" "<p>01 - " "<a href='?acao=Rele_01On'><button>ON</button></a>" "<a href='?acao=Rele_01Off'><button>OFF</button></a></p>" "<p>02 - " "<a href='?acao=Rele_02On'><button>ON</button></a>" "<a href='?acao=Rele_02Off'><button>OFF</button></></p>" "<p>03 - " "<a href='?acao=Rele_03On'><button>ON</button></a>" "<a href='?acao=Rele_03Off'><button>OFF</button></a></p>" "<p>04 - " "<a href='?acao=Rele_04On'><button>ON</button></a>" "<a href='?acao=Rele_04Off'><button>OFF</button></a></p>" "<p>05 - " "<a href='?acao=Rele_05On'><button>ON</button></a>" "<a href='?acao=Rele_05Off'><button>OFF</button></a></p>" "<p>06 - " "<a href='?acao=Rele_06On'><button>ON</button></a>" "<a href='?acao=Rele_06Off'><button>OFF</button></a></p>" "<p>07 - " "<a href='?acao=Rele_07On'><button>ON</button></a>" "<a href='?acao=Rele_07Off'><button>OFF</button></a></p>" "<p>08 - " "<a href='?acao=Rele_08On'><button>ON</button></a>" "<a href='?acao=Rele_08Off'><button>OFF</button></a></p>" "</body>" "</html>";

Step 18: Source Code - More Details of Html...

Here, I show the code I got from the Browser.

Step 19: Source Code - Responding to Request and Changing Port Status

We write the html in the buffer that will be sent to the client, and then we send the data from this buffer to this client. We verify if the request has some command of actuation on the relays.

//Escreve o html no buffer que será enviado para o cliente
client.print(html); //Envia os dados do buffer para o cliente client.flush(); //A partir daqui, verificamos se a requisição possui algum comando de //atuação sobre os relés if (req.indexOf("acao=Rele_01On") != -1) { digitalWrite(Rele_01, HIGH); } else if (req.indexOf("acao=Rele_01Off") != -1) { digitalWrite(Rele_01, LOW); }

if (req.indexOf("acao=Rele_08On") != -1)
{ digitalWrite(Rele_08, HIGH); } else if (req.indexOf("acao=Rele_08Off") != -1) { digitalWrite(Rele_08, LOW); }

Step 20: Source Code - Closing the Connection

Finally, we wait for the information traffic to be completed and we close the connection with the client.

delay(200);//aguarda para que o trafego das informações seja concluído
//Fecha a conexão com o cliente client.stop(); Serial.println("Cliente desconectado"); }

Step 21: Download the Files



    • Fix It! Contest

      Fix It! Contest
    • Creative Misuse Contest

      Creative Misuse Contest
    • Tiny Home Contest

      Tiny Home Contest