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 build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

92 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.

    Reply
  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

    Reply
    • 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

      Reply
      • 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)

        Reply
      • 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

        Reply
        • 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

          Reply
  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!

    Reply
    • 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

      Reply
    • 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);

      }

      Reply
  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?

    Reply
  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

    Reply
  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.

    Reply
  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 ….

    Reply
  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 ….

    Reply
  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é

    Reply
      • 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.

        Reply
        • 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é

          Reply
        • 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.

          Reply
  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

    Reply
  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!

    Reply
  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);

    Reply
      • 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.

        Reply
  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.

    Reply
  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 ?

    Reply
  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.

    Reply
  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

    Reply
  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.

    Reply
  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’.

    Reply
    • 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 🙂

      Reply
  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

    Reply
  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.

    Reply
  21. eines der wohl besten Anleitungen im Internet zu dem Thema!!!
    Vielen dank, du machst einem den Einstieg leicht!

    Reply
  22. Strange…
    After all of this, my Sonoff create its own wireless network “ESP-11A1AA” (name is not real, but format is).
    Then I’m able to connect to his network and control Sonoff as in this example.
    Can someone explain?
    Thank you and best wishes.

    Reply
  23. Hi Rui, good article! Do you know if this can also be applied to the Sonoff wall switches? If so, how does one accommodate the touch switch in the code or is that handled automatically by the hardware?
    Thanks

    Reply
  24. Hello everyone
    I would like to know if this file is also suitable for the R2 version with the ESP8285?
    possibly it is possible to find it suitable for this ESP8285?
    Maurizio

    Reply
  25. The flashing works fine. I have several SONOFFs to control Christmas lights. But I see from my iPhone that each device advertises an SSID to connect to, and indeed I can connect to it. I only want the SONOFFs as Wifi clients. Is there a setting that controls this?

    Reply
  26. Can you make this work with Sonoff R2?. It uses a different chip. I tried with the provided Arduino code ( I have about 10 sonoffs running this code in my house). After successfully uploading your firmware on the new sonoff, the LED becomes red and there’s nothing is displayed via the serial port. Only dots…..

    Reply
    • I am successfully using this code with the Sonoff R2. I am using VS Code as my IDE, with the PlatformIO module. There I can specify ESP8285:

      [env:esp8285]
      platform = espressif8266
      board = esp8285
      framework = arduino
      monitor_speed = 115200

      The only code changes were my Wi-Fi credentials and I added code for static IP addresses. Rui has another tutorial on how to do this.

      Reply
  27. Hi! I successfully flashed Sonoff 220V Esp8266 relay module. Thank you.
    But I need to flash another version of Sonoff relay – 5V, based on Esp8285.
    And I’ve got problem here.
    I am trying the same process:
    – Solder pin 3V3, GND, RX, TX
    – Connect pins, to the same FTDI adapter
    – Choose the right board – in this case, Generic Esp8285
    – Initialize flash mode with a button
    – Upload Blink sketch

    And nothing – «Connecting…….._____….._____…..»
    I tried different options of Uploader. In wane.
    Can you help or give an advice?

    Reply
    • Two guesses: First, swap Rx and Tx on one end, and second, dry solder in header; that is bad soldering of one or more pins. Let us know. …greg

      Reply
  28. Hi .super thanks.
    I’m looking for an e-stop feature for safety. HTML Button which quickly ends ,break the action on wifi, server,client. Is there such a function in the libraries <ESP8266WiFi.h> <WiFiClient.h> <ESP8266WebServer.h> ????

    Reply
  29. Hi I’m also trying to get this working. I have a Sonoff BASIC, the motherboard is v1.3, with an ESP8285.

    I connected the board via FTDI as described. On this version of the motherboard, in order to boot in flashing mode, it’s necessary to ground the “key” (by connecting 2 of the 4 solder points under the fat mains wire traversing the board).

    I seem to have flashed the chip sucessfully, but cannot get any response from the web server.

    Is this script written in C? I was expecting to write some micropython with this board.

    Thanks for the great tutorial, and to anyone who can help with the updated boards.

    Reply
    • I have repurposed Sonoff Basics both with Arduino-flavor C++ and Tasmota. I assume that Tasmota is written in C++ as well. If you want to use Micropython, you’ll need to flash it with Micropython first and at least for starters, do your programming via the serial port. Doesn’t really sound like a project I’d want to do. Probably too resource-constrained.

      Reply

Leave a Comment

Download Our Free eBooks and Resources

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