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.
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.
I’ve soldered 4 header pins, so that I can easily connect and disconnect wire cables to my Sonoff device.
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.
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
3) Toggle the switch to apply power to the Sonoff circuit
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> <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();
}
Preparing your Arduino IDE
Having your Sonoff device still in flashing mode.
- Select your FTDI port number under the Tools> Port > COM14 (in my case)
- Choose your ESP8266 board from Tools> Board > Generic ESP8266 Module
- Select Flash Mode: “DOUT”
- 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.
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.
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!
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
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.
Hi John! I hope you are doing well. I’m glad I could help.
Thank you for continuously reading my blog, I appreciate it!
Rui
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)
You are right John, but this is programmed with the ESP SDK and as far as I’m concerned, there’s not a way of recovering the firmware.
but with Lua programming and the ESPlorer you can.
Ah, yes, thank you Rui, I didn’t think that deeply enough 😛
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
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);
}
Hi Jonh.
Thank you so much for sharing your solution.
Regards,
Sara 🙂
Hello. thanks for tutorial. Where I can buy a 3.3V FTDI ??
Thanks
Just search on eBay http://ebay.to/1EQQWjA
Most FTDIs are 5V and 3.3V. You just have to set the 3.3V with the jumper
Hi Rui,
Excellent tutorial – 1 minor issue.
The picture is reversed under the headin – Preparing your 3.3V FTDI module –
Yup, that can be confusing.
Thanks,
Rui
Gracias. lo probaré.(Thank you. test it.)
Thank you!
Rui
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?
Please double-check your network credentials…
it works as i mentioned takes 3-5 minutes to connect to my wifi. i can live with that…
one more idea- can i connect a PIR sensor to the GPIO pin on sonoff so that i can control it over the wifi as well as as a Presence switch?
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
Thank you Olof!
I appreciate your continuous support.
Have a great day,
Rui
Parabéns, excelente tutorial e excelente blog! Fico feliz por ver que o autor é um compatriota 🙂
Obrigado Nuno!
abraço,
Rui
amigo vc tem algum video em portugues
Neste momento nao.
Obrigado por visitar o meu blog.
Rui
Good tutorial!
Is it posible on this way to control the sonoff switch on and off with udp commands?
Yup, you should be able to find an example for the ESP8266 UDP with the Arduino IDE
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.
Yup, these can definitely be programmed to include that feature.
If you want simply use the app that comes with the device: https://randomnerdtutorials.com/reprogram-sonoff-smart-switch-with-web-server/
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 ….
I don’t have a good solution for the problem at the moment using the Sonoff as a standalone device, but if you have Raspberry Pi also running you could make a secure tunnel to your network with a dynds for example.
Thanks for asking,
Rui
If you don’t care about security, you can make a port forwarding on your router (+dyndns)
Exactly. Thanks Pedro
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 ….
is it ok if i will just remove the original esp8266 chip with a spare one , so i will not loose its program..
I don’t recommend desoldering the original ESP chip, I don’t think that will be a good idea.
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é
It might fry your ESP8266 chip, but I don’t know if the Sonoff has 5V tolerant pins.
Does your device still work?
Thanks,
Rui
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.
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
You don’t have the serial communication established (your ESP might not be in flash mode) or you have the wrong wiring…
Make sure GPIO 0 is connected to GND on boot up
Just swap the TX and RX wires over
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!
Thanks for letting me know and other readers Miguel!
Abraço e fico contente por ler!
Rui
hello can i insert username and pass to protect from… in this devise?and how i do it?thaks
You can add a password, but I don’t have that exact tutorial here
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 works in the opposite way in this mode, this tutorial provides more information on that subject: https://randomnerdtutorials.com/guide-for-relay-module-with-arduino/
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.
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.
Thanks for bringing that up and yes. TX->RX and RX->TX,
Regards,
Rui
One other point. FTDI’s are not the same. You may get an error with one but not another. They are cheap so buy a few on eBay.
Try to share this out on the sonoff subreddit! reddit /r/sonoff/
Thanks for sharing!
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 ?
I’m not sure, because I’ve never used that app before…
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.
You could save the current state of the device in a variable that would output in the web server in plain HTML text the current state.
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
Thanks for asking, but we don’t have any tutorials on that exact subject
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.
No, unfortunately I haven’t tried this code with that specific SONOFF..
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 🙂
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
Hi Jan.
Unfortunately, we don’t have any sketch for those switches.
We have a tutorial to hack 433MHz remote controlled sockets with the ESP8266, but I’m not sure if it will help.
Anyway, here’s the tutorial in case you find it useful:
https://randomnerdtutorials.com/esp8266-remote-controlled-sockets/
Regards,
Sara 🙂
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.
Hi Linda.
We’re using Arduino code. It is based on C/C++ programming language.
Regards,
Sara
Hello,
Thank you for proving us this great script! Its working perfectly.
Is there anyway we can convert the http to https?
Hi George.
Thank you for reading.
At the moment, we don’t have any scripts about that subject.
Regards,
Sara
eines der wohl besten Anleitungen im Internet zu dem Thema!!!
Vielen dank, du machst einem den Einstieg leicht!
Thank you 😀
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.
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
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
Have you found a way to program Esp8285 version?
I always use:
board = sonoff_basic
instead of ESP8265. Seems to work well. …greg
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?
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…..
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.
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?
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
*** Sorry, that was to be ESP8285. ***
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> ????
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.
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.
Hi Jeff, thanks for the pointers. I will take a look at both Arduino-flavor C++ and Tasmota.