20170105_125851s

Sonoff SC with MQTT and Domoticz support

Last December Itead Studio updated their Home Automation product line with a new and different product. The main difference is that it doesn’t have a relay and it’s mainly sensors and no actuator (if we don’t define a notifying LED as an actuator). The Sonoff SC is a sensor station that packs a DHT11 temperature and humidity sensor, a GM55 LDR, an electret microphone with an amplifier circuit and a Sharp GP2Y1010AU0F [Aliexpress] dust sensor in a fancy case that looks like it was originally meant for a speaker.

The device is packs an ESP8266 as expected and is compatible with the eWeLink app. But, such a collection of sensors, with 3 of them having analog interfaces, cannot be run from the single-ADC ESP8266 so Itead has thrown in a good old ATMega328P to drive the sensors and report the Espressif with the data.

The outside

The first thing that draw your attention about the Sonoff SC is it’s casing. It’s kind of a truncated hexagonal-ish pyramid with a round grid on top and a rounded bottom. Seriously, somebody had a good time designing this. It looks a lot like a intricate speaker and actually that’s what it is. The reset/flash button sticks out shamelessly from a hole labelled “Audio” on one side of the enclosure.

20170105_125958s

Side by side with the fake audio hole there is an microUSB connector that’s only for powering the device (no data lines connected) and a microSD slot. The microSD reader is connected to the ATMega328P and I’m not sure what original purpose it has but I can think on a couple of good things to do with it.

On the bottom you have 4 black screws. Remove them to gain access to the insides of the device.

20170105_125942sThe insides

20170105_131332s

Once the 4 screws are removed it can still be a little tricky to take the PCB out from the enclosure since the button shaft leaves little room to lift the PCB from the plastic holders. Meanwhile you try to remove it, take a look at the components on that bottom side of the PCB. There you can find the controllers and programming headers.

20170105_130308s

The ATMega328P microcontroller with a 16MHz crystal. The SO-8 IC is a SGM358 dual op-amp used to amplify the electret signal. You can also see a header with 5V, TX, RX, GND and RST.

20170105_130321s

On the opposite site you have the ESP8266 IC with a Winbond 1Mbyte flash memory. You can see the PCB WiFi antena and the programming header with all the needed pins plus the SDA pin. The button is attached to GPIO0 so press it while powering the board to get into flash mode.

20170105_130416s

A perspective view fo the bottom side of the PCB. Three more things to note: the jumpers in the center-top of the image connect the RX and TX lines of the ESP8266 and the ATMega328P. Left of that, by the ATMega IC you have an unpopulated ISP header. You will have to solder a 2×3 header here to program the Atmel IC. Also, you have the Electret Mic in the forefront.

20170105_131503s

The other three sensors are pleaced on a plastic holder and fit inside the cone of the device. They are hot-glued between them and using standard JST connectors, so replacing them should be no problem…

Upgrading the Sonoff SC

There are a couple of simple, almost out-of-the-box, upgrades you can do to your Sonoff SC. First you can easily replace the DHT11 termperature and humidity sensor with a more precise DHT22 (AM2302) [Aliexpress]. Both sensors are pin compatible. You can read great full comparison of them plus the Sensirion SHT71 [Aliexpress]. The DHT22 is better in accuracy and range to it’s cheaper sibling, but it also has a short life expectancy, so after all it’s a good idea to be able to replace it easily.

20170109_235753s

DHT11 and DHT22 (AM2302) side by side. They are pin compatible.

Off course replacing the sensor is not the full story, you will need to add support for the DHT22 to the firmware. More on this later on.

20170109_235853s

The DHT22 is also bigger than the DHT11. Make sure you place it so it does not protude further than the LDR capsule, otherwise you will have problems fitting everything inside the enclosure back again.

There is also an unused connector in the PCB meant for an LED. It’s driven by GPIO D7 in the ATMega328P through a 2N7002 mosfet in reverse logic (set to LOW to turn on). Remember you have an LED on the PCB as well driven by GPIO13 of the ESP8266 also in reverse logic. The 5V pin is connected directly to the USB supply, so if you have a good power supply you may as well connect here an WS2812 LED ring [Aliexpress] for some colourful notifications. You will need a GND connection too but there are quite a few available (and properly labelled) on the board already.

20170105_131628s

The LED connector side by side to the dust sensor one.

New firmware for the Sonoff SC

This custom Sonoff SC firmware is released as free open software and can be checked out at my SonoffSC repository on Github.

So after making myself comfortable with the hardware of the device I started putting together some pieces grabbing code from other projects like the ESPurna firmware. The goal was to replace the code in the ATMega328 and the ESP8266 microcontrollers to be able to integrate the Sonoff SC into my home network. That means no cloud, that means MQTT.

While doing that I have added some features that came almost for free since I had already worked on them in other projects: Domoticz support for those that use that home automation platform and a “clap monitor“. Yes. Clap your hands to switch on/off the lights.

Just like the original firmware, this custom firmware monitors temperature, humidity, noise level (in %), dust (in mg/m3) and light (in %).

Communication

First thing was to be able to send messages between the ATMega328P and the ESP8266. Itead Studio provides a simple firmware for the ATMega328P in the Sonoff SC wifi page. The firmware is a good starting point but I don’t like it’s architectured. Everything is too coupled.

So first thing was to create a communications library between both microcontrollers. I started looking for similar solutions and found out the SerialComm library by fjctp. It was almost what I was looking for but I liked the AT commands approach, one char keys are too minimal and naming is important. So I wrote the SerialLink library that allows me to:

  • Compatible with AVR and ESP8266 ICs
  • Define custom commands (the library is agnostic) like AT+TEMP
  • Query command management (AT+TEMP=?)
  • Optional automatic ACK responses
  • Tolerant to noise in the line (debug output from the other controller)
  • Callbacks for get and set values from the application
  • Custom separator (=), terminator (\n) and query (?) chars
  • Currently, it only accepts integer payloads

In the picture below you have a sample of the communication between both microcontrollers. The ESP8266 debug messages are quite verbose but only those starting with AT+… are answered by the ATMega328P. These are configuration messages “AT+EVERY=60” (set update interval to 60 seconds), “AT+CLAP=1” (enable clapping monitor) and “AT+PUSH=1” (enable message push from the ATMega328P to the ESP8266). Further down the log you start seeing MQTT messages due to push messages from the AVR about a clap code or sensor data.

comms

The SerialLink library is currently bundled into my SonoffSC repository. I will create it’s own repo soon.

MQTT and Domoticz

MQTT and Domoticz integration was easy since most of the code was already there in the ESPurna firmware. I configured the communication link for push messages so in the ESP8266 side I have a callback function that gets all the messages from the ATMega328P and dispatches them to the different outputs.

In this code fragment you can see how message keys are matched and messages are forwarded to three different clients: MQTT, Domoticz and broadcasted to websocket clients like the web interface.

bool commsSet(char * key, int value) {

    char buffer[50];

    if (strcmp_P(key, at_code) == 0) {
        mqttSend(getSetting("mqttTopicClap", MQTT_CLAP_TOPIC).c_str(), value);
        return true;
    }

    if (strcmp_P(key, at_temp) == 0) {
        temperature = (float) value / 10;
        mqttSend(getSetting("mqttTopicTemp", MQTT_TEMPERATURE_TOPIC).c_str(), temperature);
        domoticzSend("dczIdxTemp", temperature);
        sprintf(buffer, "{\"sensorTemp\": %s}", String(temperature).c_str());
        wsSend(buffer);
        return true;
    }

    ...

}

Clap monitor

Now, this is more like a game feature. Don’t know if it’s really useful but it’s certainly fun to play with. Have you ever wanted to move someone by clapping your room lights into romantic mode? Well, this feature is about that.

The algorithm for clapping recognition is somewhat hard if you want to make it reliable, remove false positives and avoid “losing” messages. It’s not certainly suited for a noisy environments (I have kids at home…). My current approach is:

  • The ATMega samples the mic analog output (amplified) in 20ms windows and calculates peak-to-peak values
  • If peak-to-peak value is higher than a certain threshold during N consecutive time windows it flags it as a clap as remembers the current time in milliseconds
  • From the second clap on it stores the time between claps (there is also some debouncing code here)
  • After the last clap times out it checks if it has recorded any intervals (so that it has sensed a minimum of two claps in a row).
  • Clap intervals are coded into binary values. The value always starts with a 1 and each interval pushes a new bit from the right ad shifts everything up. The first interval length is considered a “short” or a 0. If an interval is at least 1.5 times bigger than the first one it is read as a “long” or a 1.
  • Finally the intervals array is reset and everything starts over again

This way I can encode clapping patterns as one byte codes. Two claps are always a “short” so it will be coded as b00000010 or 2. Three claps evenly spaced in time will be a b00000100 or 4. But if you leave a longer time (less than a second) between the second and third claps you get a b00000101 or 5.

I admit it’s somewhat weird but you easily get used to it. “Clap, clap,… clap, clap” (that’s a 10) and switch on the mirror light. “Clap, clap, clap, …. clap” (that’s an 9) and there goes the living room one.

Right now clapping codes are sent by MQTT to a user defined topic. So it’s a matter of having a service somewhere in you local network translating them to MQTT topics to perform different actions. This is a my test flow in Node-RED at home:

nodered-clap

And the code of the “matching” function node is below. Those are ESPurna devices, payload 2 means toggle relay.

if (msg.payload == 9) {
    msg.topic = '/home/living/lamp/relay/0';
    msg.payload = 2;
} else if (msg.payload == 10) {
    msg.topic = '/home/mirror/light/relay/0';
    msg.payload = 2;
} else {
    msg = null;
}
return msg;

And in the future…

There are some features I’d like to add in the future. One thing is that the device has a microSD slot connected to the SPI lines of the ATMega328P. Log sensor data to an SD card could be an option here for non-connected mode.

20170105_131406s

Also I’d like to be able to map clap codes to MQTT topics, hence not needing an external service like NodeRED to do that.

A neat feature would be to be able to OTA flashing the ATMega328P form the ESP8266. It should be possible with a minimum hardware hack: wiring the RST pin in the ATMega328P header to the SDA (GPIO2) pin in the ESP8266 header to reset the AVR programatically.

Also, there are some spare GPIOs available in the board that could be used to add more sensors (the SPI header exposes 3 digital pins, but shared with the SD). Ideas?

Flashing the ESP8266

Flashing the ESP8266 is very easy since the header close to it has all the required connections (3V3, TX, RX, GND) and the button is connected to GPIO0. Press and hold the button while powering the board to set the ESP8266 into flashing mode. You will have to remove the TX jumper in the board to avoid the ATMega328P to interfere in the upload process.

My recommendation is to flash an OTA enabled firmware as soon as possible as use OTA from then on to update the ESP8266 firmware. This way you can keep the jumpers in place and debug the communications to the AVR IC.

Flashing the ATMega328P

The ATMega328P comes flashed with the Arduino bootloader so all you have to do is connect a USB to UART programmer [Aliexpress] to it and flash it from the Arduino IDE or PlatformIO. Notice that labels in the header are from the programmer point of view (weird). So wire RX to your programmer RX, TX to your programmer TX and RST to DTR. Use 5V logic. Also, you don’t want the ESP8266 interfere with the upload so remove the RX jumper that connects both microcontrollers. Actually remove both of them or the ESP8266 might complain with so much noise.

sonoff-sc-pcba

The ATMega328P comes with the Arduino bootloader so you can flash it using a USB to UART programmer (and FTDI-like). You will have to unbridge the connections to the ESP8266 to do it to avoid the ESP8266 interfere in the upload process. Photo by Itead Studio.

But, if you have an AVR programmer like the USBASP v2 [Aliexpress] below, it might be a better option to program the ATMega328P using the unpopulated ISP header in the board. This way you won’t have to disconnect the jumpers between both controllers and have a stable test bed

20170110_005549s

The USBASP programmer I use to flash the firmware in the ATMega328P

Debugging

I’m using the ISP header to flash the ATMega328P and OTA to update the firmware in the ESP8266. This way I have everything connected and I can debug both microcontrollers using two USB to UART boards.

I use only RX lines connecting the RX of programmers to the RX pins in both headers (remember: RX to RX). Grounds are shared through my computer, but you might have to connect those too for better reliability.

20170110_005853s

Test and debug. ISP for uploading ATMega328P firmware, OTA for the ESP8266 and two RX llines to get debug messages from both microcontrollers.

Interface

The application web interface is stored in the ESP8266 using the same compression techniques I use for the ESPurna firmware. Right now you can:

  • Check the current values from the sensors
  • Configure up to 5 different WiFi networks (including the option for static IP)
  • Configure the MQTT connection and topics for the different sensor data
  • Configure the integration with Domoticz
  • Change the hostname (used for the DNS discovery feature: http://myhostname.local)
  • Change the sensor update interval
  • Enable/disable the clap monitor feature

The interface is based on jQuery and PureCSS. Here you have screenshots from the pages in the interface so you can get a better idea of what it can do at this moment.

sonoffsc-0-1-0-status

sonoffsc-0-1-0-general

sonoffsc-0-1-0-wifi

sonoffsc-0-1-0-mqtt

sonoffsc-0-1-0-domoticz

Right now it’s a fully working firmware replacement for the Sonoff SC. You will maybe miss some features from the original firmware. Let me know which ones. Use Github (link below) to report issues or feature requests.

This custom Sonoff SC firmware is released as free open software and can be checked out at my SonoffSC repository on Github.

Any comments are more than welcome.

CC BY-SA 4.0 Sonoff SC with MQTT and Domoticz support by Tinkerman is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

136 thoughts on “Sonoff SC with MQTT and Domoticz support

    1. Xose Pérez Post author

      I got it from Itead. I’m not aware of any distributor atm. But it might be available from aliexpress in the future, like other Sonoff devices.

      Reply
  1. Stuart Feltham

    This is great, and I think exactly what I want for my own setup… basically just publishing of the status of each sensor over MQTT at regular intervals. I’m so impressed I will probably just use your firmware as is, but I do have one question.

    I’ve read your whole article so apologies if you’ve said this and I’ve missed it, but can I disable the domoticz integration easily? I use Home Assistant for my home automation and I don’t want that bit, but if I can avoid a partial rewrite that would make the process of getting these setup a lot quicker.

    Just as a note, the thing that excites me about this most is the possibilities that the mic has to monitor the noise in a room. I could use that to sense when someone has left a room and not turned the light off and do it automatically. EG if the noise level has been below a threshold for 10 minutes then flash the lights to indicate that the light will be turned off in 60 seconds unless noise is sensed above the threshold. I know you said you have kids so I’m sure this is a scenario you must be familiar with. 🙂

    Reply
    1. Xose Pérez Post author

      Hi
      Thanks for your comment.

      You have two options to disable Domoticz. First one is “hard” and the recommended, just set ENABLE_DOMOTICZ to 0 in code/espurna/config/general.h and rebuild. Second option is “soft”, just leave the IDX of the different magnitudes to 0.

      That’s actually a great feature and not hard to implement. I have the impression that the amplifier circuit in the SonoffSC is too sensitive, it quickly climbs and saturates the analog input. Maybe that would require some algorithmic work.

      Reply
      1. Stuart Feltham

        Thanks, for the feedback.

        I’ve just had a look at the code on Github and I could have worked that out about the Domoticz setting if I’d had a more thorough look! Sorry.

        I’ve not ordered a SonoffSC yet, money is still a bit tight post Christmas, but I hope to get round to it soon. If you had time to (and wanted to of course) do some experimentation on the occupancy sound feature I’d be very grateful for the help. I have a software background, but this kind of programming is still very new to me. I’d be delighted to help too of course if I can and I’ll give it a go when mine arrives if you’re not interested in implementing that into your software yourself. I entirely understand if you’d rather not.

        Your note about the saturated input is interesting. You said that the noise level is reported in %. What sort of sound level would cause the device to report a 100% level? I was thinking (in my brief musings) that if you allow the user to monitor the room when quiet and also when occupied then you could create a user editable threshold for when occupancy would be assumed. That way it could be used in all sorts of situations unless a background noise like a heater or fan etc is going to saturate the mic.What do you think?

        Reply
        1. Xose Pérez Post author

          Hi

          The noise input is an analog pin in the ATMega328, so it goes from 0 to 1023, I just translate it to % in code because it makes more sense to human beings. But maybe I should apply some kind of logarithmic calculation first. Anyway, it will take some time to experiment with different backgrounds. I noted than a kid talking in their higher than average tone and trying to make herself listened sometimes saturates the input.

          I’m not forgetting about the occupancy feature, but I cannot commit to work on it just now. Will let you know.

          Reply
  2. Jeff Fox

    I like Stuart’s idea of using the mic to check for room occupancy. Along with that perhaps you could add a PIR sensor if there is a good way to mount it without making ugly modifications to the case.

    Reply
    1. Xose Pérez Post author

      There is a plastic tube inside the SonoffSC where the sensors fit. Between the tube and the outside body there could be room for a PIR. A Panasonic PIR [Amazon US] for sure, maybe even one of the “standard” ones too.

      Reply
        1. Xose Pérez Post author

          That’s a good idea. Microwave sensors can sense objects moving even through doors or thin walls so the Sonoff case won’t be a problem.

          Reply
    1. Xose Pérez Post author

      I have a 12 LEDs ring and it does not fit in. Maybe a better solution would be a LED strip and stick it to the inner side of the tube. Still, the LDR might complain 🙂

      Reply
          1. Xose Pérez Post author

            Awesome!!! That’s a hack I’m going to do myself for sure. My kids will love it! Thanks for sharing!

          2. justblairthompson

            I wonder if you will have a look at my github.. I will do a pull request, but I dont expect you to use it necessarily. I wanted initially to get the rgb ring doing something (which it is).

            I also found that I needed to run comConfigure() in setup. without it my at328 was not getting instructions to start up.

            Your code is complex. I am looking to see how to control the leds using mqtt. I cant quite see if your code is listening on MQTT or simply publishing. Perhaps you can give me some pointers.

          3. Xose Pérez Post author

            I have just seen your PR. Of course I will have a look at your code.

            I see the problem with the comConfigure. Do you want to open an issue in the repository?

            I’m not subscribing to any topic in the code of the Sonoff SC. But the code base I’m using is the same as in my ESPurna firmware. Since I use an aynchronous MQTT library, all actions are executed via callbacks. You only have to create your callback method like in the example below and call “`mqttRegister(mqttCallback)“` in your setup.

            void mqttCallback(unsigned int type, const char * topic, const char * payload) {
            
            	// When connected, subscribe to the topic
                if (type == MQTT_CONNECT_EVENT) {
                    mqttSubscribeRaw(MY_TOPIC);
                }
            
            	// 
                if (type == MQTT_MESSAGE_EVENT) {
            		if (strcmp(topic, MY_TOPIC) == 0) {
            			Serial.printf("Received %s\n", payload);
            		}
                }
            
            }
            
          4. justblairthompson

            Had some success with this thanks… but then realised that the seriallink library was not going to let me pass uint32_t values without breaking loads of stuff.

            Got R, G and B values transferring via seperate AT commands now and it works well. Broke something tonight in the ESP8266 sketch, hopefully work it out tomorrow

          5. Xose Pérez Post author

            Yes, the SerialLink library only accepts integers at the moment. It would not be hard to change it to use longs so you can send 4-byte payloads…

          6. Blair Thompson

            Ah it makes no difference I think. I am pretty sure that I fixed the ESP8266 Sketch this morning,. just need to try it tonight and then I will put in a pull request,

            I could already separate out the rgb values from a mqtt message (using commas as delimiters), so I think it will work.

            Assuming it does I can then add responses from my Openhab2 rules to provide a colour status indicator.

            Starting to think of other modes:

            * Temperature indication (Green = just right, red = too hot, blue = too cold)
            * Flashing air quality warning
            * Assistive technology applications for the hard of hearing
            * Doorbell indicator
            * Silent Phone ringer

          7. Blair Thompson

            I am not brilliant with github… I have completed the changes you suggested on the pull request, but I don’t know how I am supposed to tell you that has been done. 🙂

          8. Xose Pérez Post author

            No problem. I can see your PR changes, it’s just that I had no time to review them and merge the files. Will do as soon as I can.
            Thank you very much for your code. I’m waiting for a 24 LED ring to arrive to do your hack on my Sonoff SC 🙂

          9. Xose Pérez Post author

            Great video! Thanks for sharing.
            Hope it won’t take long for my LED ring to arrive!

      1. Simon (sjp770)

        I got a 24 led ring, but its a mm or so smaller than outside diameter of the inner sensor tube. I melted down the bits it was catching on and it fits tightly. Also cut out of the mid plate of the case to allow a 2×3 pin header to be installed facing up to the sensor, now its easy to connect the rgb ring.

        Reply
          1. Simon (sjp770)

            I think the density changes on different strips / rings. You pay more to get more pixels per meter. I have a set of 4x nested ones on the way for about the same price. This time instead of a quick ebay delivery i’ll have to wait for the slow boat from China.

  3. Thomas

    Hi, I was doing exactly the same with this product. My goal was to get more precise data from dust sensor (instead of three levels from original sonoff firmware).

    I wanted to do a first test using your code but I saw you put a symlink for SerialLink.h instead of original file to github 🙂

    Anyway… good post and happy tinkering 🙂

    Reply
    1. Xose Pérez Post author

      True, got to fix that. Anyway the original SerialLink library is in the “common” folder in the same repo. Just copy it over to the “lib” and it should work.

      Reply
    1. Xose Pérez Post author

      You will first need to connect to an MQTT broker using the MQTT component. The minimum you will have to configure is the broker IP, but a more complete configuration will look like this:

      mqtt:
        broker: 192.168.1.10
        port: 1883
        username: USERNAME
        password: PASSWORD
        client_id: home-assistant-1
        keepalive: 60
        protocol: 3.1
        birth_message:
          topic: '/service/hass/status'
          payload: 1
          qos: 1
          retain: true
        will_message:
          topic: '/service/hass/status'
          payload: 0
          qos: 1
          retain: true
      

      Next you will have to configure sensors using the MQTT platform. A simple example is:

      sensor:
        - platform: mqtt
          state_topic: "/home/living/temperature"
          name: "Livingroom Temperature"
        - platform: mqtt
          state_topic: "/home/living/humidity"
          name: "Livingroom Humidity"
      

      The topics will be those defined in the MQTT tab of the SonoffSC device flashed with my firmware (actually the concatenation of the root topic plus each of the magnitude topics).

      Reply
  4. cnxsoft

    I’m trying to use Sonoff POW with Domoticz, and while I’ve create “MQTT Client Gateway with LAN interface” in Domoticz, I guess I have to create another device to get data from Sonoff POW.
    Looks at the code it seems only the relay is supported, not the power usage data, is that correct?

    Reply
    1. Xose Pérez Post author

      Hi.

      I just read your review about using the Sonoff POW with ESPurna and Domoticz. Great job. I’m glad you find ESPurna useful. I added a comment to let you know that support for telemetry data to Domoticz will be release soon (maybe this same weekend). Depending on your hardware you will be able to send active power, current, voltage, temperature or humidity.

      Besides the “MQTT Client Gateway with LAN interface” which basically enables Domoticz as an MQTT client you will need to add a “Dummy (used for virtual switches)” hardware and a virtual sensor on top of it of type “Sensor type switch”. I don’t use Domoticz myself and I find the procedure a bit confusing, but it works.

      Reply
  5. Pingback: How to use Sonoff POW with ESPurna Firmware and Domoticz Home Automation System

  6. Pingback: IOT heatpump controller - EcoRenovator

  7. Glenn Bollue

    Hi,

    Thanks for this blog, but I have an issue with my Sonoff. I did the same steps mentioned in this blog but on the webpage of my sonoff I can’t read any value and it’s also not repsonding in the Home assistant. I also included the steps that is mentioned for the Home Assistant Configuration.

    Reply
      1. Glenn Bollue

        Hi,

        Yes the filesystem is flashed too and I can see the webpage but all the boxes are empty, for some reason it is not communicating with my raspberry/home assistant. I’m pretty new to this.

        btw a friend of mine did the same steps and he can read the values of his sonoff (he don’t know what is the delta with my layout). I can’t see the messages either.

        kind regards,

        Reply
        1. Xose Pérez Post author

          By “all the boxes are empty” you mean there is no info in the web interface? No IP, ChipID, Hostname,…? I’d like to ask you to open and issue in the repository to do a proper follow-up. It helps me a lot to have everything (bugs, requests,…) in a single place…

          Reply
      2. Glenn Bollue

        Hi,

        Not sure if my reply came thru, but yes I flashed the filesystem and still no success my textboxes from the sensors are still empty. My broker is the IP coming from my raaspberry pi/ home assistant.

        kind regards,

        Reply
        1. Simon (sjp770)

          If only the sensor data is not showing maybe reflash the atmega chip? Make sure the jumpers are removed and the RST is connected to DTR. Then ensure the jumpers are back in place.

          Reply
        2. Simon (sjp770)

          I found my issue (same – no sensor values) – because I burnt out the socket on the board for the DHT11 and I neglected to replace it there is a trace carrying 5v between the two smd resistors I had broken. I now have my DHT22 on D13 in the ISP header, pulling 5v from the spare header on the top of the board, gnd from the programming header and I bridged the two SMD resistors. All fixed.

          So i’d say if you fiddled with that area of the board check your soldering.

          Reply
  8. Simon (sjp770)

    Very keen to flash the chips of the sonoff, but the arduino IDE cant compile because DebounceEvent.h is missing. Are you using a different system to flash that fetches the libraries? I’m following along with Blair Thompson after his youtube vid, and will have the neopixel ring installed as well.

    Is there room / a way to have functions like a colour sweep or fire animation stored on the arduino chip and just call them with mqtt and a duration? Really hoping to have some dynamic lighting options as well as just rgb modes.

    Reply
    1. Xose Pérez Post author

      Hi Simon

      I use PlatformIO as my development environment and it fetches all the dependencies itself, very useful. You can find the DebounceEvent library in its repo here: https://bitbucket.org/xoseperez/debounceevent. You can also download it as a ZIP file ready to install from your arduino IDE.

      I’m waiting for my LED ring too, eager to do Blair’s hack on my Sonoff SC. And I know myself and I know I will add more functionality to it. Taking note of your idea. Thank you!

      Reply
      1. Simon (sjp770)

        Thanks for the links. Sorry for requesting them over on the espurna bitbucket issue tracker! I’m still new to git type repos. When I go to flash the atmega328p i get the following:

        avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
        An error occurred while uploading the sketch

        Is it because ive chosen the wrong board type or programmer within Arduino IDE? if so could you detail the settings I need to flash it?

        One last query – could you run the RGB ring off the ESP8266? Scargills blog and superhouse.tv detail how to upgrade the memory chip if storage of code is a limitation.

        Reply
        1. Xose Pérez Post author

          The error is probably due to a bad wiring: TX and RX are mislabelled, you should connect TX in the board to your programmer TX line, same for RX; also connect RST to DTR. The board is a Arduino/Genuino UNO compatible.
          The RGB ring code could be moved to the ESP8266, sure. It was Blair’s decision to do it in the atmega328. The SonoffSC uses a 1Mbyte memory chip for the ESP8266, it’s more than enough to store several animations and thousands of other stuff on it.

          Reply
  9. Simon (sjp770)

    Any more info on troubleshooting? I have both flashed now and get the RGB rainbow flash on my neopixel ring, but the web interface doesnt show any values for any of the sensors. Also are the mqtt topics just as per the web interface or is there anything else on them? The TASMOTA firmware for the sonoff was /cmnd/sonoff/power but the web interface only showed /sonoff as the topic.

    Do you have the topic and payload to send RGB values to the Sonoff SC?

    Reply
    1. Xose Pérez Post author

      For the sensors you can define the topics in the web interface (root topic + sensor topic). The only one not there yet is the RGB that is fixed to root topic + “/rgb”. The payload is a 3 number string comma separated, each value being from 0 to 255. So if you want to set it read send “255,0,0”. At the moment is only allows single colors.

      Reply
  10. Ewald Harmsen

    This guide is fantastic! Thanks!

    Do you know if it is possible to just flash the ESP8266 chip with ESP easy?
    Will it still be able to receive the data from arduino and sent it to domoticz?

    Reply
    1. Xose Pérez Post author

      Don’t think ESPEasy has support for the custom messages the ATmega328 is sending (either the factory ones or the ones I defined). You should ask in the ESPEasy forum.

      Reply
  11. MiKa

    Hi,
    My Sonoff SC is still in AP mode, i configured network parameters but cannot connect to WiFi network, not working with fix IP and with DHCP too. Wifi have hidden SSID… Some reccomendations?
    MiKa

    Reply
    1. Xose Pérez Post author

      It’s probably due to the hidden SSID. You can modify the wifi.ino file and modify the line that says:

      jw.scanNetworks(true);

      to

      jw.scanNetworks(false);

      Reply
  12. Miroslav Kartal

    Hi,
    I cant connect my Sonoff SC to my Wifi Network.
    I configured and double check all parameters, Device is still in AP mode, dont work fith fix IP and DHCP too
    Some hints?
    Regards,
    MiKa

    Reply
  13. Simon (sjp770)

    Worth noting the v1.1 of the PCB has the DHT11 directly soldered to the board. I failed to replace it as the solder wouldnt grip to the holes after I had removed the old sensor.

    Reply
    1. Xose Pérez Post author

      Oh! Bad news. The firmware supports both sensors and even thou the DHT22 is not my favourite it is certainly better than the DHT11.

      Reply
      1. Simon (sjp770)

        Which pins are available to connect to on the 2×3 pin header? I’m thinking of a fix for my temp probe. Looks like I need a resistor from the 5v to the data pin, but 5vdc and gnd are exposed on the 2 pin header on the top of the board, just need a free data pin thats not the one im using for rgb.

        Reply
  14. Santi

    Hi Xose,

    I am thinking to buy the sonoff sc with the 1 Channel Inching /Self-Locking WiFi Wireless Switch 5V to control my gas boiler using the cloud of itead. The problem is that I have read the temperature sensor has +-2ºC of accuracy and it is a lot of a house.

    can I change it by the dht22 with the original firmware or it is necessary change the firmware?

    thanks

    Reply
    1. Xose Pérez Post author

      Hi Santi

      The original firmware does not support the DHT22, or at least there is no documentation on how to do it. And since Itead’s cloud is not open source and no public API available, you will have to decide weather to use a better sensor or use Itead’s Cloud.

      Reply
  15. falk

    I can second the detail about the DHT11 soldered to the board in rev.1.1 – also my SC came without the Jumper for the TX and RX pins. There is one other thing – I am not sure the dust sensor can work the way it is now – normally it needs an airflow through the hole. I will maybe print something that will force the warmed up air from below (warmed by the electronics) through the hole.

    I will try to add a CO sensor later as well but that’s for the future since they are still on their way.

    Reply
    1. Xose Pérez Post author

      Hi Falk

      You are probably right about the dust sensor, since 11st January the maximum value it has reported has been 0.21 mg/m3…

      Reply
  16. D-mah

    Hello Xose,

    first of all thanks a lot for your great job!
    I’m trying to get my Sonoff SC run but I have some minor issues.

    I flashed the ESP and ATMega as well.
    WiFi Connection is established with Sonoff SC but I can’t see any UI from web.
    I’ve typed the credentials in, but afterwords nothings appear.

    Do you have an idea what is happening?
    Thanks in advance!

    Reply
    1. Xose Pérez Post author

      You have to flash the filesystem image too… If you are using PlatformIO just type “`pio run -t uploadfs“` from the esp8666 folder of the project. If you are using the Arduino IDE take a look at the section in the Arduino Core for ESP8266 wiki about uploading files to the file system. The files to upload are already in the data folder, where the SPIFFS Uploaded tool will look for them.

      Reply
      1. D-mah

        Hi Xose,

        thanks for your fast reply!
        At least I switched to platformio IDE, due to issues with Arduino IDE. There it worked like a charm, thanks a lot!!

        I’m using now Sonoff_Sc with FHEM via MQTT, works perfect!

        Reply
        1. Xose Pérez Post author

          Great. I strongly recommend using PlatformIO. But just out of curiosity: what problems did you face with Arduino IDE?

          Reply
          1. D-mah

            I had problems to flash the SPIFFS filesystem. In detail I got following error:

            SPIFFS_write error(-10001): File system is full.

          2. Xose Pérez Post author

            The Sonoff SC comes with a 1MByte flash memory. When building your project from Arduino IDE be sure to select “Flash Size: 1M (128K SPIFFS)” from the tools menu.

    1. Xose Pérez Post author

      I don’t. But you can check the video tutorials by Andreas Spiess or Blair Thompson in Youtube. They both cover the Sonoff SC with hardware and software modifications.

      Reply
  17. martin

    when i will flash with plattformio i get the error sonoffsc-master/esp8266/sonoffsc/comms.ino:9:24: fatal error: SerialLink.h: No such file or directory

    Reply
    1. Xose Pérez Post author

      The SerialLink library is in the “common” folder in the repo. If you are using Arduino IDE you will have to “install” the ZIP file in “Sketch > Include library > Add .ZIP library” form the IDE.

      Reply
  18. Juan

    Hi Xose,

    I have created an issue at sonoffsc github:, Embedis EEPROM dictionary doesn’t work with SerialLink.

    Hope you can take a look. Have you tested embedis terminal at esp8266 serial interface of SonoffSc ?.
    I was not lucky getting responses.

    Regards.

    Reply
    1. Xose Pérez Post author

      Embedis commands are disabled because I did find they were not compatible with serial communication with the ATMega328. The parser is handled in the settingsLoop method which is not being called in the main loop.

      Reply
  19. Jon-Magne Johansen

    Would it be possible to include the SonoffSC code in the normal ESPurna code? Of course just the ESP code. In that way, the Atmega could be handled as a normal sensor.
    I use Domoctiz, but the SC code has a bug, so no readings is passed to Domoctiz.
    Compare the domoctiz sections of the SC code with the same in the ESPurna code, and note that the sprintf.. lines are different.

    Reply
    1. Xose Pérez Post author

      ESPurna and the ESP8266 part of my SonoffSC code share a lot of code, still they are different products. I don’t really see a need for that. Of course I can change my mind but at the moment I don’t feel like investing time in this. If you find a bug in the SonoffSC code please report it to the issues sections in the repo.

      Reply
  20. Learn Smart

    Can you help me? I do not know how to configure and control MQTT_RGB_TOPIC MQTT information in homeassistant,this is no working:

    – platform: mqtt
    name: “sonoffsc RGB”
    state_topic: “/test/sonoffsc/rgb/status”
    command_topic: “/test/sonoffsc/rgb/switch”
    #brightness_state_topic: “/test/sonoffsc/rgb/brightness/status”
    #brightness_command_topic: “/test/sonoffsc/rgb/brightness/set”
    rgb_state_topic: “/test/sonoffsc/rgb/rgb/status”
    rgb_command_topic: “/test/sonoffsc/rgb/rgb/set”
    state_value_template: “{{ value_json.state }}”
    #brightness_value_template: “{{ value_json.brightness }}”
    rgb_value_template: “{{ value_json.rgb | join(‘,’) }}”
    qos: 0
    payload_on: “ON”
    payload_off: “OFF”
    optimistic: false

    Reply
    1. Xose Pérez Post author

      I have not modified my SonoffSC to add Blair’s hack but plan to do so soon. Then I’ll be in better position to answer your question.

      Reply
  21. Roger

    Excellent work.Many thanks for you!

    The DUST sensor, I felt it so inaccurate. Waiting for a update firmware with RGB light control.

    Reply
    1. Xose Pérez Post author

      The main problem with the dust sensor is that there is no air flow inside the enclosure. Adding a small fan (how or where I don’t know) would probably improve the range of values.

      Reply
  22. Vadim

    Hi, I am just wondering what I need for this project. Do I need USBasp USB ISP 3.3V / 5V AVR Programmer only? Or I need this one as well: FT232RL FTDI USB 3.3V 5.5V to TTL Serial Adapter ?
    Or I need both? I am not planning to debug, just want to flash to this firmware that has great Cloud independent interface. Please help!

    Reply
    1. Xose Pérez Post author

      You will need the FTDI board to flash the ESP8266 in the SonoffSC. I used the USBasp to flash the ATMega328 but you can also flash it using the FTDI, only it’s a little more involved since you have to remove the jumpers to flash it and connect them again to test it, every time. If you plan to just flash it once and forget the FTDI might be all you need, but bugs happen 🙂

      Reply
  23. Andi

    Hi,
    a really cool projekt. Fun and joy to read 🙂

    I didn’t have a closer look at your code yet. What I was thinking on first sight:
    What about using retained messages for MQTT sensor data?
    define MQTT_SKIP_RETAINED 1 => 0

    If you do a simple “has value changed since last meassure” and only send it as retained after a change, it would reduce bandwith and energy.

    And for it seems as if theese little devices would multiply themself, it might be worth thinking about.

    Greetings

    Reply
    1. Xose Pérez Post author

      It is worth thinking about, for sure. A lot of my sensors just report the same value over and over, like: “door closed”, “door closed”, “door closed”. Of course my house door is only opened a few times a day and for a brief time. Same with these MQTT devices. But at the same time these repetitive messages double as heartbeat messages. I guess the point is to be able to tune it to your needs.

      Reply
  24. Learn Smart

    can you help me? if i use the ESPurna Firmware(Version 1.7.1) ,DebounceEvent library Version can not support SC Firmware,can you update DebounceEvent library to support ESPurna Firmware(Version 1.7.1) and SC Firmware both of them。

    Reply
    1. Xose Pérez Post author

      That upgrade shouldn’t be too difficult but I’ll be soon working on the SC, so yes 🙂

      Reply
    1. Xose Pérez Post author

      I see. No, ESPurna does not support the PSB-04. I suspect it uses the same protocol as the DUAL, with a Silicon Labs F330 handling the buttons and relays, but I have no way to test it.

      Reply
          1. Xose Pérez Post author

            This is not the same device you previously linked from Itead. This one is based on the PSF-B85 (a carrier for the ESP8285), not the PSB-04.

  25. George Pucci

    Great Work !!

    I just flash my Sonoff(version 1.1 – DTH soldered in the board) today but it show weird temperature (640) and humidity (1512) values !!! I dont change DHT11 sensor, so i leave DTH_TYPE parameters with DHT11. Before update firmware, Itead app show correct values !!

    Reply
    1. Xose Pérez Post author

      Don’t have a 1.1 version. Things to check:
      * GPIOs are the same?
      * Does it have a pull-up for the data line?

      Reply
      1. George Pucci

        Sorry, 1.1.0 is the version of debounceevent !!! I find the error. Need to change the setting in plataformio.ini file too !! Now all is fine !!

        Thanks !!

        Reply
  26. George Pucci

    After 4 days working, my Sonoff SC stops to show values in the sensors fields !! I just flash atmega again (Atom + IFTDI + all wires + remove the jumpers), upload process ok, but no luck with the sensors !!

    Reply
    1. Xose Pérez Post author

      Hi
      Why don’t you open an issue on Github to found out what’s going?
      Thank you

      Reply
      1. Peter

        I left a reply further up on this issue. I have also seen it. It seems that the 328 misses the AT+PUSH=1 command and sometimes just sits there waiting for it. I discovered this while I had debug console and sent it manually and everything came back. Also changing the update frequency gets it going again. Timing issue perhaps?

        Reply
        1. Xose Pérez Post author

          Do you mind opening an issue on github for this? It will be better tracked there. Thanks!

          Reply
  27. Nico Copica

    Hello and thank you for your work!

    I’m having an issue with the web interface. I have flashed the ATMega and the ESP with success. I am able to connect to the Sonoff SC through Wifi. The password is asked and authentication seems successful. But then nothing happens, I can’t see any interface.

    Would you have an idea of something I did wrong or is there a way to access to settings by another way ?
    Thank you

    Reply
      1. Nico Copica

        Thank you so much! I flashed SPIFFS using the Arduino IDE and I can now access to UI.

        Reply
  28. Peter

    Hi

    Tried to compile using both PlatfromIO and Arduino IDE. It seems the DebounceEvent library may have changed as I am getting this error in either platform.

    C:/Users/HA/CloudStation/Platform.io/sonoffsc-master/esp8266/sonoffsc/button.ino: In function ‘void buttonLoop()’:
    C:/Users/HA/CloudStation/Platform.io/sonoffsc-master/esp8266/sonoffsc/button.ino:23:33: error: ‘class DebounceEvent’ has no member named ‘getEvent’
    uint8_t event = _button.getEvent();
    ^
    C:/Users/HA/CloudStation/Platform.io/sonoffsc-master/esp8266/sonoffsc/button.ino:25:22: error: ‘EVENT_DOUBLE_CLICK’ was not declared in this scope

    if (event == EVENT_DOUBLE_CLICK) createAP();
    ^
    C:/Users/HA/CloudStation/Platform.io/sonoffsc-master/esp8266/sonoffsc/button.ino:26:22: error: ‘EVENT_LONG_CLICK’ was not declared in this scope
    if (event == EVENT_LONG_CLICK) ESP.reset();
    ^

    Reply
    1. Xose Pérez Post author

      The SonoffSC code uses version 1.1 of the DebounceLibrary, but latest version in the repository is 2.0. You can either checkout tag 1.1 or change the dependency line in platformio.ini to
      “https://bitbucket.org/xoseperez/debounceevent.git#1.1.0”

      Reply
      1. Peter

        LOL thanks I posted this then almost immediately saw the issue in Github. Anyway I now have the right lib. Thanks and great work. I was thinking of doing this myself but why re-invent the wheel so to speak.

        Reply
  29. Peter

    Xose I also have the issue where it seems I cannot get out of AP mode. I am not sure how to make the SC connect to my WiFi access point so I can connect it to my mqtt broker. I have added the WiFi details correctly and pushed RECONNECT button but it just comes back into AP mode. Also when it comes back it loses the WiFi password and I have to re-enter it again. Also sensor data is empty so I guess it’s not talking to the 328. Sorry to trouble you.

    Reply
    1. Xose Pérez Post author

      Do you have the option to connect it via serial to your computer to debug? You can easily add the proper commands via the command line (connected to the ESP8266, that is). You can do:

      set ssid0 YOURSSID
      set pass0 YOURPASS
      reconnect
      

      And you should see the log of the connection process.

      About the communication with the ATMEGA, again, in the debug console you should be seeing the messages from the ATMEGA328 as AT commands (AT+TEMP=25, for instance). If you don’t see anything maybe you have not flashed the ATMEGA properly.

      Reply
  30. Peter

    Yes I can see Serial. Keeps looping with “Scanning” and says no known networks found. I try and set it via Serial but it doesn’t accept any commands. When I connect to the units AP and the Webpage I see [WEBSERVER] Request: GET / on console until the next “Scanning” happens and then it kicks me off the AP and I have to reconnect. Sensors show as ZERO. I don’t have USBAsp but when I connect to the 328 I see AT+HELLO1 so the 328 is responding but I cannot see the flow between them unfortunately.

    Reply
  31. Peter

    Xose sorry about multiple messages. You may delete them. I can confirm that the 328 is working correctly. If I send AT+EVERY=30 I get a sensor reading which is populated with numbers no problem. Clap detector is also working with AT+CODE=2. So it leaves all issues in is ESP it seems. One thing I haven’t done is install GULP? Could this be the issue?

    Reply
  32. Peter

    Xose I have it going. I have no idea why but it seems the flash was corrupt on the ESP. I filled it full of 0’s started everything from scratch and I have it working. Thanks for your great work, Obviously you don’t need to publish this if you don’t want to 😀

    Reply
    1. Xose Pérez Post author

      Sorry, I’ve been busy lately but I’m happy to see you have sorted it out. Yes, I have also had that issue before and flashing again solves the problem.

      Reply
  33. Steve Lenehan

    Love the system you have created – works well. I have one query, you have defaulted the Domoticz support to writing to the nvalue’s whereas many of their standard Domoticz devices expect the updates to arrive in the svalue field. I am currently intercepting and converting in node-red but if you were to revisit this can I suggest an option on the Domoticz status page that you could add a pair of tick boxes by each index to allow the installer to choose svalue or nvalue feeds for that index. Thanks again

    Reply
    1. Xose Pérez Post author

      I’m not a Domoticz user myself so I’m ot familiar with some of the specifics.

      May I ask you to open an enhancement issue on bitbucket for this? Thank you!

      Reply
  34. Russ

    Hi.. I Just flashed the ESP8266 firmware and I can see that an wifi AP is available but can’t find the password. Sorry but just spent hour going through all the scripts trying to find it.. Can you help please?

    Reply
    1. Xose Pérez Post author

      The default password is “fibonacci”, it’s defined in the general.h file.

      Reply
      1. Russ

        Thanks very much. I did eventually find the password. But then I realised when I had flashed the esp firmware with arduino that I didn’t include the SPIFS part.
        Again found after several hours found that for me this only worked with Arduino 1.65 r5 (1.66 and 1.8 Not working ) also using version 0.2.0 of the ESP8266FS plugin worked wheras 0.3.0 Not working.
        I could then upload the SPIFS. But then I found the gz files needed to be extracted first from gz type to their proper files.
        Once this was done flashed the atmega firmware and was up and working.

        Only issue I have now is sending the sensor data to Domoticz part. The mqtt seems to be in the wrong format. I see an error in the domoticz log.

        2017-05-20 07:28:45.338 Error: MQTT: Invalid data received!
        2017-05-20 07:28:45.438 MQTT: Topic: domoticz/in, Message: {“idx”: 1706, “nvalue”: 43, “svalue”: “”}.
        This is the same for all the sensors.

        For now as a work around I am going to change the payload in node red and then send to domoticz.

        One other thing that might be useful. I noticed that the same mqtt server address as the domoticz server. It might be useful to be able to define these separately? (for instance I have my main mqtt broker on another pi than my domoticz)

        Apart from these small things . Thanks for an excellent piece of work

        Reply
        1. Xose Pérez Post author

          Hi
          The documentation in my Sonoff project is non-existant, I know, and that’s something I’d like to change when I have the time to do it. Maybe you could add an issue to the repository for the format thing, don’t know right now what’s going on there. As for the rest: hopefully I will be updating the code soon and flashing the SPIFFS “partition” will no longer be necessary. And the MQTT server you should be able to change it from the web interface and point it anywhere. The only thing is that both Domoticz and the SonoffSC should be using the same broker (or two different brokers bridget together).

          Reply

Leave a Reply (all comments are moderated, be patient)