Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building an ESP8266 Internet Connected Four-Relay Switch

DZone's Guide to

Building an ESP8266 Internet Connected Four-Relay Switch

Why have one switch when you could have four? This design lets you harness four relays for your lights instead of just one, all over Wi-Fi.

· IoT Zone
Free Resource

In this tutorial, we will cover how to a build Wi-Fi-enabled, Internet-controlled switch connected to EasyIoT Cloud with four relays and one ESP8266. We will use the Arduino IDE to program the ESP8266.

This Internet-connected switch is a simplified version of my ESP8266 internet connected switch. The program code is simplified — it's not plug-and-play, with a hard-coded configuration, but it uses four relays instead of just one. You can easily extend the program to control more relays with a single ESP8266. Relays can be controlled from anywhere in the world — you just need an Internet connection.

Devices can be controlled over the EasyIoT Cloud interface or the native Android application.

WARNING!! You will play with LIVE MAINS!! Deadly zone!!

If you don't have any experience and aren't qualified to work with MAINS, I wouldn't encourage you to play around!

Do NOT use this without proper knowledge about MAIN circuits and without a proper FUSE.

Max current for solid state in this tutorial is 2A — suitable for room light only. 

Introduction


Materials

  • ESP8266 Wi-Fi module
  • Relay module
  • 3.3V power supply
  • 4.7K Resistor
  • NPN Transistor TO-92 2N2222

EasyIoT Cloud configuration 

First, register to EasyIoT Cloud. We will add DO modules manually. Go to Configure->Modules. If there are demo modules, you do not need to delete them all. Press Add Module. Change the module type to Digital Output DO (MT_DIGITAL_OUTPUT) and save it. It's important to remember the module ID. If this is your first module in your configuration, the module ID should be 1. Next, add more DO modules, in our case three more, but it can be dependent on your program and number of relays.

The program is written in the Arduino ESP8266 IDE. Check out the Arduino ESP8266 IDE tutorial to see how to connect a ESP8266 module to a computer to upload a program. The program can be downloaded from our GitHub. You will also need the MQTT client library. Add this library to the library folder in the Arduino IDE. Our program uses the EasyIoT Cloud MQTT API.

In the program, change the EasyIoT Cloud username and password:

#define EIOTCLOUD_USERNAME "xxx"

#define EIOTCLOUD_PASSWORD "xxx"

Also, set up your Wi-Fi access point name and password:

#define AP_SSID "xxx"
#define AP_PASSWORD "xxx"  

If you use different DO pins than the default D0, D1, D2, D3, change those pins.

In the program, also change the module ID to correspond to those in the user interface:

#define MODULE_ID_1     1

#define MODULE_ID_2     2

#define MODULE_ID_3     3

#define MODULE_ID_4     4

#include <ESP8266WiFi.h>
#include <MQTT.h>

#define AP_SSID     "xxx"
#define AP_PASSWORD "xxx"  

#define EIOTCLOUD_USERNAME "xxx"
#define EIOTCLOUD_PASSWORD "xxx"

// create MQTT object
#define EIOT_CLOUD_ADDRESS "cloud.iot-playground.com"

#define DO_TOPIC        "/Sensor.Parameter1"

#define PIN_DO_1         D0  // DO pin1 
#define MODULE_ID_1     1


#define PIN_DO_2         D1  // DO pin2 
#define MODULE_ID_2     2


#define PIN_DO_3         D2  // DO pin3 
#define MODULE_ID_3     3


#define PIN_DO_4         D3  // DO pin4 
#define MODULE_ID_4     4


MQTT myMqtt("", EIOT_CLOUD_ADDRESS, 1883);


void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);  
  WiFi.begin(AP_SSID, AP_PASSWORD);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(AP_SSID);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  };

  Serial.println("WiFi connected");
  Serial.println("Connecting to MQTT server");  

  //set client id
  // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);
  clientName += "-";
  clientName += String(micros() & 0xff, 16);
  myMqtt.setClientId((char*) clientName.c_str());

  Serial.print("MQTT client id:");
  Serial.println(clientName);

  // setup callbacks
  myMqtt.onConnected(myConnectedCb);
  myMqtt.onDisconnected(myDisconnectedCb);
  myMqtt.onPublished(myPublishedCb);
  myMqtt.onData(myDataCb);

  //////Serial.println("connect mqtt...");
  myMqtt.setUserPwd(EIOTCLOUD_USERNAME, EIOTCLOUD_PASSWORD);  
  myMqtt.connect();

  delay(500);

  pinMode(PIN_DO_1, OUTPUT); 
  pinMode(PIN_DO_2, OUTPUT); 
  pinMode(PIN_DO_3, OUTPUT); 
  pinMode(PIN_DO_4, OUTPUT); 

  subscribe();
}

void loop() {
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}


String macToStr(const uint8_t* mac)
{
  String result;
  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);
    if (i < 5)
      result += ':';
  }
  return result;
}


void subscribe()
{
    myMqtt.subscribe("/" + String(MODULE_ID_1) + DO_TOPIC); //DO 1
    myMqtt.subscribe("/" + String(MODULE_ID_2) + DO_TOPIC); //DO 2
    myMqtt.subscribe("/" + String(MODULE_ID_3) + DO_TOPIC); //DO 3
    myMqtt.subscribe("/" + String(MODULE_ID_4) + DO_TOPIC); //DO 4
}


void myConnectedCb() {
  Serial.println("connected to MQTT server");
  subscribe();
}

void myDisconnectedCb() {
  Serial.println("disconnected. try to reconnect...");
  delay(500);
  myMqtt.connect();
}

void myPublishedCb() {
  Serial.println("published.");
}

void myDataCb(String& topic, String& data) {  
  if (topic == String("/"+String(MODULE_ID_1)+ DO_TOPIC))
  {
    if (data == String("1"))
      digitalWrite(PIN_DO_1, HIGH);     
    else
      digitalWrite(PIN_DO_1, LOW);

    Serial.print("Do 1:");
    Serial.println(data);
  }


  if (topic == String("/"+String(MODULE_ID_2)+ DO_TOPIC))
  {
    if (data == String("1"))
      digitalWrite(PIN_DO_2, HIGH);     
    else
      digitalWrite(PIN_DO_2, LOW);

    Serial.print("Do 2:");
    Serial.println(data);
  }


  if (topic == String("/"+String(MODULE_ID_3)+ DO_TOPIC))
  {
    if (data == String("1"))
      digitalWrite(PIN_DO_3, HIGH);     
    else
      digitalWrite(PIN_DO_3, LOW);

    Serial.print("Do 3:");
    Serial.println(data);
  }

  if (topic == String("/"+String(MODULE_ID_4)+ DO_TOPIC))
  {
    if (data == String("1"))
      digitalWrite(PIN_DO_4, HIGH);     
    else
      digitalWrite(PIN_DO_4, LOW);

    Serial.print("Do 4:");
    Serial.println(data);
  }

}


The easiest way to test program is to use an ESP8266 LUA node MCU board. Just connect it via USB port and you can test the program. If you use this board, you can also uncomment #define DEBUG to see debug messages. The Flash button on the ESP8266 board will work as a button to manually change switch state. The onboard LED displays the switch state.


Hardware

In our case, we use NODEMCU ESP8266, but you can use any other type of ESP8266 with all pins exposed. In our program, we connect D0, D1, D2, and D3 in a circuit, which controls the relays. The relays are using 5V. ESP8266 is using 3.3V. To connect the 3.3V ESP8266 to the 5V relay module, we use one NPN transistor 2N2222. The connection is shown below:

The GND is common, the ESP8266 is on 3.3V, and the relay module is on 5V. You can use a relay module with more relays (2, 4, 8).

EasyIoT Cloud web interface

EasyIoT Cloud Android application

And there's your switch! As a note, modules can be manually renamed in EasyIoT Cloud configuration to suit your needs!

Topics:
esp8266 ,tutorial ,iot ,wi-fi ,home automation

Published at DZone with permission of Igor Jarc, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}