Reprogram Sonoff Smart Switch with Web Server

In this post, you’re going to learn how to flash custom firmware in the Sonoff device, so that you can control it with your own web server. I recommend that you read my previous post to get familiar with the Sonoff. We also have additional resources that describe how to flash a custom firmware to the Sonoff device using an FTDI programmer and the Arduino IDE. 

If you don’t have a Sonoff yet, you can get one for approximately $5 – visit Maker Advisor to find the best price.

First, watch the step by step video tutorial below

Safety warning

Make sure you disconnect your Sonoff from mains voltage. Then, open the box enclosure.

warning-m

Sonoff pinout

The Sonoff is meant to be hacked, and you can see clearly that these connections were left out, so that you can solder some pins and upload a custom firmware. That’s the pinout.

sonoff_gpio-r

I’ve soldered 4 header pins, so that I can easily connect and disconnect wire cables to my Sonoff device.

pins-soldered

Preparing your 3.3V FTDI module

You need an FTDI module to upload a new firmware to your Sonoff. Use the schematics provided as a reference.

Warning: uploading a custom firmware is irreversible and you’ll no longer be able to use the app eWeLink.

I’ve added a toggle switch in the power line, so that I can easily turn the Sonoff on and off to flash a new firmware without having to unplug the FTDI module.

I used hot glue to glue the ends of the wires together. This prevents you to make wrong connections between the FTDI and the Sonoff in the future.

hot-glue-ftdi

Boot your Sonoff in Flashing Mode

To flash a new firmware to your Sonoff, you have to boot your Sonoff in flashing mode. Follow this 4 step process:

1) Connect your 3.3V FTDI programmer to your computer

2) Hold down the Sonoff button

hold-down-sonoff-button

3) Toggle the switch to apply power to the Sonoff circuit

apply-power-to-sonoff

4) Then, you can release the Sonoff button

Now, your Sonoff should be in flashing mode and you can upload a new firmware.

Opening the Arduino IDE

You should have the ESP8266 add-on installed in the Arduino IDE – If you don’t have the add-on installed, first follow this tutorial on How to Install the ESP8266 Board in Arduino IDE.

You can upload the full sketch to your Sonoff (replace with your SSID and password):

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

int gpio13Led = 13;
int gpio12Relay = 12;

void setup(void){
  webPage += "<h1>SONOFF Web Server</h1><p><a href=\"on\"><button>ON</button></a>&nbsp;<a href=\"off\"><button>OFF</button></a></p>";  
  // preparing GPIOs
  pinMode(gpio13Led, OUTPUT);
  digitalWrite(gpio13Led, HIGH);
  
  pinMode(gpio12Relay, OUTPUT);
  digitalWrite(gpio12Relay, HIGH);
 
  Serial.begin(115200); 
  delay(5000);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  
  server.on("/", [](){
    server.send(200, "text/html", webPage);
  });
  server.on("/on", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio13Led, LOW);
    digitalWrite(gpio12Relay, HIGH);
    delay(1000);
  });
  server.on("/off", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio13Led, HIGH);
    digitalWrite(gpio12Relay, LOW);
    delay(1000); 
  });
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop(void){
  server.handleClient();
} 

View raw code

Preparing your Arduino IDE

Having your Sonoff device still in flashing mode.

  1. Select your FTDI port number under the ToolsPort > COM14 (in my case)
  2. Choose your ESP8266 board from ToolsBoard > Generic ESP8266 Module
  3. Select Flash Mode: “DOUT”
  4. Press the Upload button

Wait a few seconds while the code is uploading. You should see a message saying “Done Uploading”.

Troubleshooting

If you try to upload the sketch and it prompts the following error message:

warning: espcomm_sync failed
error: espcomm_open failed

It means that your Sonoff is not in flashing mode. You’ll need to repeat the process described in section “Boot your Sonoff in flashing mode” described earlier in this guide.

Final circuit

After uploading the code, re-assemble your Sonoff. Be very careful with the mains voltage connections.

It’s the exact same procedure as shown in the introductory guide.

sonoff_circuit

ESP8266 IP Address

Open the Arduino serial monitor at a baud rate of 115200. Connect GPIO 0 of your ESP8266 to VCC and reset your board.

After a few seconds your IP address should appear. In my case it’s 192.168.1.70.

esp ip address

Demonstration

For the final demonstration open any browser from a device that is connected to the same router that your Sonoff is. Then type the IP address and click Enter!

web-server

Now when you press the buttons in your web server you can control the Sonoff switch and any device that is connected to it.

Sonoff tutorials list:

Wrapping up

That’s it for now, I hope you had fun learning about the Sonoff device. Make sure you subscribe to my blog, because I’ll be posting more tutorials about the Sonoff.

Do you have any questions? Leave a comment down below!

Thanks for reading,

Rui


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

75 thoughts on “Reprogram Sonoff Smart Switch with Web Server”

  1. Another great tutorial Rui! For me though; I think the Sonoff is a good “off the shelf” item if one needs to control only one device. In my case I’ve used one of your earlier projects that demonstrate 2 led on/off control, and added 3 more to control 5 under-cabinet puck lights. I’ve also built a garage control to open/close the door, and turn on/off the 3 strings of fluorescent lights, for a total of 4 control circuits. But again this tutorial helps build understanding of IoT in general. Thanks for all you do.

  2. Good tutorial. Maybe to create new tutorial how to dump current/original sonoff firmware before uploding custom one.

    So after playing users can upload original back in.

    Kind regards,
    Kristijan Modric

    • Thanks for the suggestion Kristijan. I don’t think it’s possible to do that at the moment and the manufacturer doesn’t provide the original firmware.
      I have a warning for readers saying that after flashing the firmware it’s irreversible and you are on your own.

      Thanks,
      Rui

      • Rui, regarding the question about dumping the original firmware to save for later use. I recall “downloading” files in EXplorer to the editor window. would something like that work? Also vaguely remembering something similar in Lualoader (I think LOL)

      • Hi Rui,

        Are you sure you can’t save initial firmware from Sonoff device?

        Because this device use standard ESP8266 and if you use esptool.py you can read_flash or write_flash.

        And you can’t protect it from dumping. On this forum link I find that:
        https://forum.wemos.cc/topic/181/backup-original-firmware-with-esptool some guy made backup of initial Wemos firmware with this command:

        esptool.py –port /dev/tty.wchusbserial1410 –baud 115200 read_flash 0x00000 0x400000 wemos-original.bin

        Alos find that someone alredy dumped Sonoff initial firmware on this site:
        https://github.com/arendst/Sonoff-MQTT-OTA

        The initial firmware from api/sonoff/user1.bin can be flashed using the SDK 1.4 provided bin files with the following esptool.py command line: esptool.py –port /dev/ttyUSB0 write_flash -fs 8m 0x00000 boot_v1.4\(b1\).bin 0x01000 user1.bin 0xFC000 esp_init_data_default.bin 0xFE000 blank.bin

        You know those stuff much better than I.

        I stiil waiting my sonoff device to arrive, so can’t test on my own.

        Kind regards,
        Kristijan

        Kind regards,
        Kristijan

        • Thanks for your helpful comment Kristijan. I was referring that the manufacturer doesn’t provide the original firmware.
          After you reflash the Sonoff you are on your own.

          Thanks again,
          Rui

  3. Great tutorial! Question though, is there anyway to force a static IP address instead of using DHCP? This way you always know what IP address will be assigned to each Sonoff. Also since you are setting up a web server could I send it commands from a script to turn on/off? Say I have a central control system (Mister House or similar) that can send URL commands to that IP address, would it work if I sent the ON or OFF page from the system? Thanks for all the tutorials, going to buy your course today!

    • Yes, you can either assign an IP address in your router to your Sonoff MAC Address or you can search for “static IP address ESP8266 Arduino IDE” with a few changes to my sketch, you’ll be able to do that.

      That’s a great suggestion. I might do the script that you’re looing for as a future tutorial.
      I’ll be actually start creating some project examples with PHP in a couple of weeks.

      Thanks for reading,
      Rui

    • To add a Static IP.. add/Update this. You will need to change the xxx’s to the correct values for your network.

      WiFi.begin(ssid, password);

      IPAddress ip(xx,xx,xx,xx);
      IPAddress gateway(xx,xx,xx,xx);
      IPAddress subnet(xxx,xxx,xxx,xxx);
      WiFi.config(ip, gateway, subnet);

      I also added a small section to enable the built in button to toggle the relay.

      In the loop section add this:

      if(digitalRead(gpio0Btn)==LOW) {
      if(digitalRead(gpio12Relay) == HIGH){
      digitalWrite(gpio13Led, HIGH);
      digitalWrite(gpio12Relay, LOW);
      }else{
      digitalWrite(gpio13Led, LOW);
      digitalWrite(gpio12Relay, HIGH);
      }
      delay(1000);

      }

  4. Great tutorial 🙂 Thanks Rui…However i have one problem. It is taking a lot of time for connecting to my wifi. serial Monitor shows …………………………………………………………………………….. and never really connects. I tried static IP as well as DHCP. Any hints?

  5. Hello Rui,

    I love this tutorial and can say, you are great!!! I learn everyday from you new tools and new features. I tell all my colleagues about your courses. Go on with your wunderfull work and you will keep me forever as a menber!!

    Regards
    Olof

  6. Only just found out about these and they look exactly what I’m after.

    My question is this:- Can the wifi work both ways so an app can interrogate the switch status? If you log in remotely it would be good to check if it’s on or not with actual feedback – and not just assumed from the interface software. Great site, info and tutorials by the way!!

    Your project and tutorials are excellent by the way.

  7. Hello.
    First of all, a great tutorial.

    How can i manage my sonoff with my 4G connection or with dyndns account ???? Have you got any solution.

    Thanks a lot in advance ….

  8. Hi again and thanks a lot for the previous answer.

    One more question.
    With this turtorial can i give sonoff a static IP and change the port from 80 to 8080 or what ever i want?

    Thanks a lot again ….

  9. Hi Rui,

    Thanks for your good tutorial. I have a question, what happens to the ESP8266 when you connect it to 5V FTDI? (While being a novice I missed that there were two voltages available…. )

    Cheers René

      • Well I do not really know if it still works, after I connected w 3.3V FTDI I was able to load your code without error. But it does not do anything…. No LED… No new ip on my network.

        • Hi Rui,

          I got anew one 🙂 and the story continues.
          With the setting 1M (64K SPIFFS) I uploaded the new sketch and got that confirmed.
          But still no connection to my WiFi (double and triple checked the credentials)
          When I open the serial monitor I get the following after a while:

          ets Jan 8 2013,rst cause:4, boot mode:(3,6)

          wdt reset
          load 0x4010f000, len 1384, room 16
          tail 8
          chksum 0x2d
          csum 0x2d
          v09f0c112
          ~ld

          Any suggestions on what goes wrong?

          Many thanks René

        • Hi!

          I had similar problem. Try this settings in IDE:

          Board: Generic ESP8266
          Flash mode: DOUT
          Flash size: 1M (no SPIFFS)
          Debug port: Disabled
          Debug level: None
          Reset method: ck
          Crystal F: 26mhz
          Flash F: 40mhz
          CPU F: 80Mhz
          Upload speed: 115200
          port: /dev/ttyUSB0 (or in windows COM…)

          This worked for me.

  10. Hi, great guide but unfortunately not working for me. I don´t know what I´m doing wrong.
    If you are willing to help me then I can paste the picture of connections.

    My goal is to flash espeasy firmware to use sonoff in Domoticz.
    Unfortunately still getting this error in when flashing

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

    It can be that I´m not in flashing mode, but follow your guide.

    Any help much appreciated.

    Thanks
    Vojta

  11. Hi Rui,

    I had the same issue as Chaitanya, it was not connecting. I then changed the flash size (in Tools in the Arduino IDE) to 1M (64K SPIFFS) and it worked right away! Hope this helps somebody that has the same issue.

    Regards

    PS: também fiquei contente por encontrar um tutorial de origem nacional!

  12. Hi Rui, I think there is a mistake in your code. At boot the relay is turned On et LED off!
    It is probably better to turn the relay OFF:

    // preparing GPIOs
    pinMode(gpio13Led, OUTPUT);
    digitalWrite(gpio13Led, HIGH);

    pinMode(gpio12Relay, OUTPUT);
    digitalWrite(gpio12Relay, LOW);

      • The relay switches ON straight away on power up or mains power reboot (led does not light); to be clear, my mains lamp comes ON without any command when power is first applied but the led on the Sonoff is off. After using the web interface just once then its all works ok, but if there was a power interrupt or fail then the device being controlled by the Sonoff is supplied with mains power straight away on reboot. It should be fail safe and the other way around.

  13. Thank you for such an excellent post! One minor remark – please make it very clear in your post that RX is connected to TX. A newbie like myself will just look at “http://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2016/11/sonoff_gpio-r.jpg?resize=750%2C424” and connect to FTDI’s equivalent pins.
    You should also add “Check that you connected TX to RX” to the Troubleshooting “warning: espcomm_sync failed” section.

  14. Hi, thanks for your tutorial.I have find this ap Evothings Viewer play.google.com/store/apps/details?id=com.evothings.evothingsviewer&rdid=com.evothings.evothingsviewer , for controlling ESP8266WebServer. , is good idea use it?
    Is normal who my Sonoff button not working ?

  15. This works nearly perfectly for my needs. Thank you for this.

    I am wondering, though, is it possible to show the current state of the relay? I’m programming with PHP/AJAX etc and would like the page to show it the relay is on or off.

  16. Do you have code for sonoff 4ch. I bought 4 of them from Ali express. They all connect for the first time and are easily added in e-we link but after few minutes they go offline. Tried all the solution but still same problem. I want to control all switches on local lan instead through Internet with my own app on my android

  17. Rui, excellent tutorial. I made it and it works very good. However I would like to use Sonoff to control a 24V AC solenoid and I purchased some Sonoff SV boards. Have you ever tried this code on the Sonoff SV board ? Thanks.

  18. Great Tutorial Rui. I have modified some of these…if you cut the left hand side leg of the LED and connect it to GPIO14 you can program the button to toggle the relay, and the LED show green for ‘On’ and red for ‘Off’.

    • Hi Paul.
      That’s a great idea!
      Thank you for the suggestion. I’m sure lot of our readers will find that useful:)
      Regards,
      Sara 🙂

  19. Thank you for perfect tutorial,
    I want to ask, do you have a sketch for model with 433mhz radio. I bought more sonoffs, which have wifi and 433mhz. I have wall switches with 433mhz transmitter, so I need both, wifi and radio too.

    Your tuts are awesome, thanks for all of them…

    Jan

  20. Thank you that was helpful, I am trying to build a GUI to control ,my radiator though Th16 Sonoff. What language is your code in above please.

Leave a Reply to Jairo Cancel reply

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.