We write our firmware for the Sonoff TH10 / 16 modules


    Recently at Geektimes there was a review about ITEAD TH10 modules . I want to share the experience of developing my own firmware for these devices.

    SONOFF is a series of switches, sockets, and other devices of the Internet of Things category from ITEAD . They are characterized by a rather low price, the use of the “popular WiFi module” ESP8266 and work in their own service located in the Amazon AWS global server cloud.

    There are third-party firmware for these modules. For example, MQTT OTA, assembled with the ESP SDK or the same thing, but in the Arduino IDE

    I want to share the experience of creating my own firmware on Sonnoff in the Ardiono IDE.

    I liked the Sonoff modules right away. Starting from the packaging:



    Appearance:





    High-quality assembly and soldering:





    And ending with a well- developed circuitry , in which transistors for controlling the load, pull-up and matching resistors and condors are clearly not spared.





    By supporting and documenting their devices, ITEAD can plug in the belt of many eminent manufacturers who do not bother to publish technical details on their hardware. And the ITEAD product list is quite impressive.

    In essence, the Sonoof TH10 / 16 is an ESP8266 with a network power supply, peripherals in the form of relays, LEDs, temperature and humidity sensors, with a connection block and in a decent case.



    I will omit the description of how to connect Sonoff to a cloud service and manage the eWeLink application on a smartphone. In my opinion, it is completely inapplicable when controlling controllers depends on the Internet and an account in some kind of cloud, albeit on Amazon servers. Therefore, we leave the eWeLink application to demonstrate the capabilities of Sonoff and write our control program.

    To do this, solder a 4-pin connector for connecting to a USB / TTL converter.



    Having a negative Sonoff POW flashing experience, I highly recommend that all programming work be done with the Sonoff power unit disconnected and powered via a 3.3V pin.

    The last USB / TTL I heroically died with the Sonoff POW module, so I use to connect the Arduino UNO with a RESET pulled to the ground. Una's 3.3-volt stabilizer copes with the load in the form of the ESP8266 and the entire periphery of the module.



    As a development environment, I will use the Arduino IDE for the ease of installation and the abundance of ready-made libraries and examples, although as a programmer with experience I still think that VI and make are quite enough for developing programs of any complexity ))).

    How to install the ESP8266 Cire for Arduiono IDE is devoted to a lot of materials on the Internet. From myself I want to recommend the version of Arduino IDE 1.6.5 , as having the least glitches when working with ESP.



    Since the memory chip is installed on the board with 1 MB, we select the appropriate configuration when loading into Board Manager:



    Now just press the Sonoff controller button and distort the power, the device goes into firmware download mode.



    In order to program the controller yourself, you need to understand which ports are connected to. To do this, you can use the scheme on the ITEAD website, the link to which I cited above and the tester.

    So what we have:

    GPIO0 - button (this is understandable when we
    turned on the bootloader) GPIO12 - red LED and relay
    GPIO13 - blue LED
    GPIO14 and GPIO4 are output to the sensor connection socket.

    Moreover, both sensors are single-wire and use GPIO14. GPIO4 still need to enable a jumper on the board.

    Yes. Not a lot, although more than ESP01.

    GPIO2 and GPIO15 have pull-up resistors on the board, you can solder to them. GPIO5 and ADC are not soldered anywhere and you need to connect directly to the ESP chip. We leave these four conclusions alone and proceed with programming.

    Sonoff flashing LED sketch
    /**
    * Прошивка SONOFF TH10/16
    * Copyright  2016 Алексей Шихарбеев
    * http://samopal.pro
    */
    #include 
    uint8_t PIN_RELAY =   12;
    uint8_t PIN_LED2  =   13;
    void setup() {
       pinMode(PIN_RELAY,OUTPUT);
       pinMode(PIN_LED2, OUTPUT);    
    }
    


    LEDs work in antiphase. Blue lights up when it is low. The relay should not operate due to lack of 5V power. In the future, I will use the blue LED to display various modes. I wrote about this in

    detail in this article . I will not dwell on the button in detail. Yes, I wrote a convenient library of button controls, which catches a long and short press, auto-repeat with a long press and crushes contact bounce. I described all this in detail in my blog .

    Now the sensors. They sent me an AM2301 temperature / humidity sensor and a DS18B20 temperature sensor in a waterproof version.



    AM2301 is compatible with the DHT21 sensor. It needs a DHT library to work. There are a great many forks of the DHT library, I recommend taking a version from Adafruit which has auto-tuning for the controller frequency and which works correctly on ESP8266 .

    Sensor Sketch AM2301
    /**
    * Прошивка SONOFF TH10/16
    * Copyright  2016 Алексей Шихарбеев
    * http://samopal.pro
    */
    #include 
    // DHT от Adafruit 
    // https://github.com/adafruit/DHT-sensor-library
    #include  
    uint8_t PIN_DHT = 14;
    DHT dht(PIN_DHT, AM2301); 
    void setup() {
    // Последовательный порт для отладки
       Serial.begin(115200);
       Serial.printf("DHT init ...");
       dht.begin(); 
    }
    void loop() {
      delay(1000);
      Serial.print("Temperature=");
      Serial.print(dht.readTemperature(),1);
      Serial.println(" C");
      Serial.print("Humidity=");
      Serial.print(dht.readHumidity(),0);
      Serial.println("%");
    }
    




    To connect the DS18B20 you need the OneWire library. The multi-platform version of this library is fully compatible with ESP.

    We take the sensor polling algorithm from an example:

    Sketch of working with the DS18B20 sensor
    /**
    * Прошивка SONOFF TH10/16
    * Copyright  2016 Алексей Шихарбеев
    * http://samopal.pro
    */
    #include 
    // Мультиплатформенная библиотека
    // https://github.com/PaulStoffregen/OneWire
    #include 
    #define ERROR_VALUE 2147483647
    float  GetDS18X20();
    uint8_t PIN_DS = 14;
    OneWire ds(PIN_DS);
    void setup() {
    // Последовательный порт для отладки
       Serial.begin(115200);
       Serial.printf("DS18B20 init ...");
    }
    void loop() {
      delay(1000);
      float t = GetDS18X20();
      if( t!= ERROR_VALUE ){
         Serial.print("Temperature=");
         Serial.print(t,1);
         Serial.println(" C");
      }
    }
    /**
    * Опрос датчика температуры
    */
    float  GetDS18X20(){
      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius;
      if ( !ds.search(addr)) {
    //    Serial.println("DS18B20: No more addresses.");
        ds.reset_search();
        delay(250);
        return ERROR_VALUE;
      }
      if (OneWire::crc8(addr, 7) != addr[7]) {
    //      Serial.println("DS1820: CRC is not valid!");
          return ERROR_VALUE;
      }
      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          type_s = 1;
          break;
        case 0x28:
          type_s = 0;
          break;
        case 0x22:
           type_s = 0;
          break;
        default:
    //      Serial.println("Device is not a DS18x20 family device.");
          return ERROR_VALUE;
      } 
      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end
      delay(1000);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.
      present = ds.reset();
      ds.select(addr);    
      ds.write(0xBE);         // Read Scratchpad
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
      }
      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      return celsius;
    } 
    




    Well, the peripherals are working. Further I use my existing practices. You can take all of the firmware from here.

    Features of the firmware:
    • Automatic detection of AM2301 and DS18B20 sensors
    • Long press of the button - on / off access point mode
    • Short press of the button - on / off relay
    • Blue LED is on - connection is established, double flash - no connection, single blinking - access point mode
    • Local WEB server in access point mode 192.168.4.1
    • when connecting to WiFi at the IP address that is configured
    • Password access authorization. Default admin / 12345
    • Saving parameters to a server on the Internet with a normal HTTP request. You can configure any server, for example, folk monitoring. And you can local without any Internet.
    • Saving settings to EEPROM
    • When connected to the Internet, set the time via NTP





    For lovers of ready-made services. the ready-made library MQTT, BLYNK, etc. is easily screwed. But this is already beyond the scope of this article.

    Total


    SONOFF is a convenient platform, first of all, for those who can independently develop and modify control programs.

    Those who are familiar with the ESP8266 - Sonoff is saving on assembly, soldering and parts, provided that you need such a device configuration as is laid down in a specific Sonoff module.

    The biggest drawback of these modules is that part of the GPIO is not wired to connectors. Well, what should ITEAD do with an 8 pin comb and get all the free GPIOs from ESP there. I think the popularity of such modules at the current price would greatly increase.

    As for specific applications, such a controller can be implemented on the Sonoff TH10 module.

    Also popular now: