Hackster is hosting Hackster Holidays, Finale: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Tuesday!Stream Hackster Holidays, Finale on Tuesday!
Rizwan Ahmed
Published

ESP-01 based Sonoff wireless smart switch

Control all the appliances by just one tap. An IoT based Smart appliance controller using ESP-01

IntermediateFull instructions provided3 hours7,363
ESP-01 based Sonoff wireless smart switch

Things used in this project

Hardware components

ESP8266 ESP-01
Espressif ESP8266 ESP-01
×1
MIC29150 3.3BT
×1
Aimtec power supply
×1
240VAC 3A Solid state Relay
×1
BC547 NPN transistor
×1
MCT2E
×1
5 mm LED: Red
5 mm LED: Red
×1
5 mm LED: Green
5 mm LED: Green
×1
Resistor 1k ohm
Resistor 1k ohm
×2
2 pin pcb terminal
×1
Pushbutton switch 12mm
SparkFun Pushbutton switch 12mm
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

ESP-01 based Sonoff Switch Controller

Code

ESP-01 based Sonoff Switch Controller

Arduino
#include <FS.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <EEPROM.h>

WiFiServer server(80);
String state;
String val;
int LED = 2;
bool mustSaveConfig = false;

const char* ssid = "ADD_YOUR_CUSTOM_SSID";  //This SSID will be displayed on                                                  WiFi search list 
const char* password = "ADD_YOUR_CUSTOM_PASSWORD"; //You can add your custom                                                        password

char API[30] = "12345678910112131415161718";   //Here you can add your customAPI                                                  to be stored permanently 
char savedAPI[30] = ""; //Used for comparing

void saveConfigCallback()
{
  Serial.println("Should save Config");
  mustSaveConfig = true;
}

void setup()
{
  EEPROM.begin(512);
  Serial.begin(115200);
//  readData();

  SPIFFS.format();
  Serial.println("Mounting FS...");

  if (SPIFFS.begin())
  {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/cconfig.json"))
    {
      Serial.println("reading the config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile)
      {
        Serial.println("opened config file");
        size_t size = configFile.size();

        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;

        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if(json.success())
        {
          Serial.println("\nparsed json");
          strcpy(API, json["API"]);
        }
        else
        {
          Serial.println("failed to load json.config");
        }
      }
    }
  }
  else 
  {
    Serial.println("Failed to mount FS");
  }
  WiFiManagerParameter custom_API("API", "API", API, 31);  //Created Custom                                                                   Parameter

  WiFiManager wifimanager;
  wifimanager.setSaveConfigCallback(saveConfigCallback);
  //wifimanager.setSTAStaticIPConfig(IPAddress(192,168,1,114), IPAddress(192,168,1,1), IPAddress(255, 255, 255, 0));
  wifimanager.addParameter(&custom_API);
  wifimanager.resetSettings();

  wifimanager.autoConnect(ssid,password);
  Serial.println("Connected");

  strcpy(API, custom_API.getValue()); // Comparing the API with sored API
  if (strcmp(API, savedAPI) != 0)
  {
    
  }
  else 
  {
    Serial.println(" ");
    Serial.println("Wrong API");
    Serial.println("Please Enter Correct API");
    delay(60000);
  }

  if (mustSaveConfig)
  {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject &json = jsonBuffer.createObject();
    json["API"] = API;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile)
    {
      Serial.println("Failed to open config file for writing");
    }
    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
  }
  server.begin();
  Serial.println(" ");
  Serial.println("Server Connected");
  Serial.println("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.println("Gateway IP: ");
  Serial.println(WiFi.gatewayIP());
  Serial.println("Subnet IP: ");
  Serial.println(WiFi.subnetMask());
  
}

void loop()
{
  WiFiClient client = server.available();

  if (!client)
  {
    return;
  }
  state = client.readStringUntil('\r');
  Serial.println(state);
  client.flush();
  if (state.indexOf("/on") != -1)
  {
    digitalWrite(LED, LOW);
    val = "on";
  }
  else if (state.indexOf("/off") != -1)
  {
    digitalWrite(LED, HIGH);
    val = "off";
  }
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Conent-Type: application/json\r\n\r\n";
  s += "{\"data\":{\"message\":\"success\",\"value\":\"";
  s += val;
  s += "\"}}\r\n";
  s += "\n";

  client.print(s);
  delay(1);
  Serial.println("Client Disconnected");
}

Credits

Rizwan Ahmed
4 projects • 1 follower
A junior IoT engineer who likes to play with the Arduino and Raspberry Pi to gain skills and knowledge

Comments