Flashing the Sonoff TX/T0 US Version

The latest version of the Sonoff “smart” light-switch, the TX, is significantly different from the older ones. For a start, Itead have taken notice and created the front-panel for the US version in portrait, rather than landscape orientation. However, as one of the other changes was to remove all of the graphics (barring a small “Sonoff” label along the bottom), the orientation hardly matters now, anyway.  There’s also a black version available (and the Itead  site photo of the new, graphics-free front panel with blue, LED backlighting shows this version).Black version showing switch back-light

The new, plain white (or black)  front panel is fairly thick, with a single slot on the bottom edge for levering it open from the main body of the switch  —  which is required before you can fit it in the wall. The thickness of the front panel means that removing it from the body before it is fitted into the wall is a little difficult; while the front panel doesn’t flex, the thinner plastic of the body twists alarmingly. The best way to overcome this seems to be to lay the whole device on a flat surface, face down, then firmly press down with one thumb on the screw mounting hole (on the back-plate, just above the slot) before using a large, flat-bladed screwdriver to lever the back-plate away from the front panel. It does take quite a bit of force to open it.Press firmly & lever open

Removing the front panel allows you to screw the main body into the wall cavity, but also gives us access to the PCB so that we can flash TASMOTA onto the ESP8285 controller before fixing it into its permanent home.

The top PCB (with the switches and the ESP8285) needs to be disconnected from the main body of the device before programming and pulls off fairly easily (the design is asymmetric, so the PCB can only be inserted back into the body in one way).  The PCB layout also seems to have changed quite a bit since the previous version and there’s no “TP2/GPIO0” test point on the reverse side of this board.  Luckily, the other common connection point, the pad on R19, is still available, but in a different position on the PCB.Position of GPIO0 on R19

GPIO0 is on the end of R19 which is closest to the ESP8285 chip (the larger of the two chips, on the R/H side of the photo).

The contacts for a (3.3 volt) USB adapter are visible on the bottom, R/H side of the PCB photo (click to enlarge) and, as usual, GPIO0 needs to be briefly connected to ground when powering up the device to put it into programming mode.  I just used a flying lead clipped to ground at one end, touching the other end against the resistor pad while connecting the 3v3 supply.  Programming instructions for the “T1” version of the switch still work for this version.

Version 7 of TASMOTA is now available and the template for the T1/TX is also available from GitHub,  simply choose the correct template for your specific device and copy the string from the web page, then select Configure->Configure Other from the main menu on your newly installed device, paste the text into the Template input section, tick the Activate box and hit save.  Once the ESP has rebooted you will see the toggle boxes for each of the individual switches at the top of the main menu.

There be bees here…

If you’ve never sat close to a bee hive and watched the little ladies going about their business, you’ve missed one of natures treats.  They are fascinating creatures on their own and the social cohesion and workings of the hive make them doubly so.  Bee keepers have always had to tread the delicate line between upsetting the balance of daily life in the hive against it’s internal state and the general welfare of the bees, though.  We have traditionally had to open the hives on a regular basis to check on the health of the bees themselves, as well as the state of honey and food stores.  While we still need to keep a careful eye on the health of the bees, IoT and ingenuity are making it easier to look after the bees without having to disrupt the hive with such frequent openings and I was very pleasantly surprised to come across the OpenHiveScale project a couple of days ago.

This is a new and ingenious take on a perennial favourite; a method of monitoring the weight of a beehive and thus being able to judge the amount of stored honey (summer) or food supplies (winter), without having to open the top of the hive and pull out individual frames of comb to inspect them (which always disrupts the hive, no matter how careful the beekeeper is).

The problem initially looks easy to techies.  Just pop a digital scale under the hive and automate sampling of the weight reading to have it delivered directly to your smart-phone.  Unfortunately, if you’ve tried going down this route, you will have discovered for yourself that it’s not quite that simple.  Digital scales (and load sensors in general) don’t deal well with being in a loaded condition for long periods of time (they tend to drift in a non-linear manner) and even if they did, there is still the problem of constantly supplying power to the scale at some remote (sometimes -very- remote) site.  One of the other options is to use a mechanical scale and somehow collect the data (the common low-tech version of this has a cheap, mechanical bathroom scale in a wooden housing under the beehive with some sort of mirror arrangement to allow the beekeeper to monitor the weight on his visits to the apiary).

OpenHiveScale mechanismThe OpenHiveScale project overcomes these problems by using a design based on the ancient “Steelyard” balance, with its sliding weight mechanism.  The fulcrum is folded within the frame to provide a wide load capability in a compact package.  The sliding counterbalance weight is driven by a stepper-motor and belt combination, with the “smarts” for the whole system provided by an ESP8266.  

The whole of this project (electronics, PCB, mechanical build and firmware) are all available from the OpenHiveScale GitHub repository.  Unfortunately, comments in the code are few and far between and there are no real build instructions on the site (there is an assembly_manual.pdf in the “mechanical” directory of the repository, but it is limited to diagrams, without any narrative), so you might have a difficult job duplicating their original work.  The good news is that they do sell kits.  The bad news is that they’re currently out of stock (and the price, including postage, is over €200).

The controller is modular, so if the hive is outside of WiFi coverage, an optional GSM, LoRa or SigFox card can be added (for an extra €30 to €40) to increase the range.

Power consumption is kept to a minimum by using an RTC chip to gate the enable signal on an LM3671 (low quiescent current) regulator and the recommended power source is a pack of 3 x AA alkaline batteries.

Unfortunately, the price (and lack of specific build details) make this a non-starter for all but the most well-heeled beekeepers, which is a shame.  We can only hope that this unique design will become popular enough to make it into mass production (with, hopefully,  a resulting drop in price).  It’s easy to imagine other applications for this scale, too.  Anyone who relies on tanked propane gas, for instance, would welcome the convenience of knowing just when the tanks need to be switched over (instead of having to go out at 10:30 at night, still wet and soapy from an interrupted shower).

 

 

TASMOTA now supports the A4988 stepper-motor controller

As of a couple of days ago,  courtesy of Tim Leuschner, TASMOTA now supports the A4988 stepper-motor controller board.  Here are Tim’s instructions for getting it going:-

How to use:-

1. Physically connect at least Dir-&STP-Pin of the A4988 to 2 free GPIO’s of the ESP.
2. Allocate those GPIOS in settings to “A4988 pins” (#170ff).
3. In console type MOTOR {“setMIS”:1,”setRPM”:60,”setSPR”:200,”doTurn”:1.5} (sets microstepping to 1/1, StepsPerRevolution to 200, RevolutionsPerMinute to 60 and commands the motor to turn one and a half rotations).
MOTOR {“doMove”:100} commands the motor to step 100 times.
MOTOR {“doRotate”:360} commands the motor to rotate 360 degrees.
4. REST-Calls work with : http:///cm?user=aName&password=aPW&cmnd=MOTOR%20{%22setSPR%22:200,%22setRPM%22:60,%22doMove%22:360}

Command list:-

setMIS — Sets the micro-stepping (1,2,4,8,16 stand for a full step, or one-half, one-quarter, one-eighth or one-sixteenth of a step).
setSPR — Sets the number of steps the motor requires for one full rotation (depends on micro-stepping).
setRPM — Sets the number of revolutions per minute (roughly – not precise) – if too high, motor will not turn – test out an appropriate number for your use case.
doMove — Commands the motor to step the given number of times.
doRotate — Commands the motor rotate the given number of degrees.
doTurn — Commands the motor to spin the given number of rotations.

Tim is also looking for a little help with the MQTT implementation of the command set:-

Can someone plz take care to enable the MQTT-way to send this commands?Cheers Tim

Any takers?

A more detailed instruction sheet on how to set up the A4988 (with power switching and control of micro-stepping using additional GPIOs) has already been added to the Wiki by the hard-working maintainers (I don’t know how they keep up with all of the updates).

First steps with the W600 (on Linux)

I ordered a couple of these W600 dev boards a few weeks ago, as they were reported to be the easiest ones to use when introducing yourself to the ThingsTurn Dev BoardW600 chip (these “ThingsTurn” boards don’t have any second processor to grapple with, but do have a UART chip and USB connector for easy power/comms).

It turned out that while the power connection was easy, the comms were anything but and I wasted far too much time messing around trying to get it to accept an upload or even just a terminal connection.  So today’s post mainly consists of a series of short tips on how to get started with the W600 “ThingsTurn” dev board without pulling out all of your hair.  Tips 1 through 4 deal with getting MicroPython onto your W600, while those from #5 onwards are examples of what you can do with the board from the MicroPython REPL (command line).

For my purposes, I just wanted to upload MicroPython as a quick, functional test, without having to download and install a toolchain and/or SDK, or really do anything at all that took more than a couple of lines of typing or 5 minutes of my time.  Two days later, I was -still- getting nowhere very fast; my blood pressure was rising and I was itching to use my magic, solves-everything tool  …the 1.5kg lump hammer.

So, tip #1 is  —  Don’t believe everything you read (including this!).  The W600 firmware and applications are still under heavy development.  Most (but not all, see tip #2) of that work is taking place in China.  The translation and maintenance of the manuals seems to be quite well down the TODO stack (something that most of us are guilty of).  Specifically, don’t bother trying to use their “download.py” (if you can find it) for anything, most especially not for uploading to ThingsTurn boards.

Tip #2  —  Volodymyr Shymanskyy has recently posted a great tool for uploading to the W600.  It knows about the two available bootloader methods and will try to do the right thing, depending upon which type of file you’re attempting to upload.  Don’t bother with anything else; go straight to his repository and start using it now.

Tip #3  —  Don’t assume that your favourite terminal program(s) will work with the ThingsTurn boards, even if it has worked with everything else you’ve ever tried it with.  It turns out the the the ThingsTurn boards (note that I’m being very specific here, as I don’t believe that any of the other W600 modules suffer from this issue) have a requirement for the RTS signal to be held at “0” when connecting, otherwise the W600 will be forced into a permanent reset condition.  I was unable to get either “screen” or “minicom” (my usual goto choices for comms terminals) to play with the ThingsTurn boards.

By this time I knew that the boards worked, as they communicated with “w600tool” easily and loaded MicroPython (to displace the simple, one-second flash on/off program which comes as default on the boards).  Connecting with either screen or minicom would very occasionally produce a random, brief flash from one of the blue LEDs, but there was never any further indication of life and definitely nothing coming from the boards.  A major step forward was finding that sending a “Hang-Up” request (CTRL-A H) from Minicom produced the MicroPython header and a REPL prompt from the board, before it lapsed back into its previous, comatose state.  This confirmed that the upload had indeed worked and that, given the right conditions, MicroPython would run.  At this point I reverted back to my 1980’s RS232 self and started writing a simple C program to toggle the control lines…  before remembering that this was the glorious future and somebody else on the ‘net had undoubtedly already done it (and undoubtedly made a far better job of it than I ever did).  So I knuckled myself on the side of the head a couple of times and turned back to Volodymyr Shymanskyy, as he’d already helped me out once and seemed to have already cracked this particular problem.  That particular rabbit-hole led me, in very short order, to Python.

Tip #4  —  Use the force, Luke!  Or at least, don’t be as stupid as me and refuse to see what’s right under your nose.  You wanted to get running with something quickly:-  MicroPython.  MicroPython =~ Python.  W600tool =~ Python.  There’s a bit of a pattern emerging here.  Yup, those clever Python dev guys have already written the solution to our problem and it is called “miniterm”.  A quick check of the on-line manual pages showed that it was quite capable of toggling selected hardware control lines and holding them in the selected state, as well as all of the normal port and baud selection stuff.  So here’s the command line to get you connected, up and running using miniterm:-


python3 -m serial.tools.miniterm --rts 0 /dev/ttyUSB0 115200

[…and just a reminder here that this is from Linux, you’ll likely have to change at least the device name if you’re using a different OS].

Once you’ve typed that in you’ll see something like:-

— forcing RTS inactive
— Miniterm on /dev/ttyUSB0 115200,8,N,1 —
— Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H —

…followed by an ASCII-art representation of the Winner-Micro (stacked “W” and “M”) logo (which really confuses WordPress formatting, so is not included here), followed by:-

WinnerMicro W600
MicroPython v1.10-279-g3c60627-dirty on 2019-05-24; WinnerMicro module with W600
Type “help()” for more information.
>>>

Yay!  We’re in business!


Tip #5  —  Import the machine-specific hardware module.  Configure a W600 pin (PB14 in this case) as an output (with no pull-up or pull-down) and assign name “led14” to it.  Use the assigned name to toggle the value of the W600 pin (note that the blue LEDs on the ThingsTurn boards have their anodes connected to VCC via a 1k resistor and the cathodes are connected to the GPIO pins, so the output value of “1” turns the LED off and “0” turns it on:-


>>> import machine
>>> led14=machine.Pin(machine.Pin.PB_14,machine.Pin.OUT,machine.Pin.PULL_FLOATING)
>>> led14.value(1)
>>> led14.value(0)


Tip #6  —  Connect to an existing Access Point.  To do this, we first import the network module and then initialize as a station and scan for available networks.  We connect to an available network (SSID “BigHouse”) with whatever the password is (“Th3Pa55word” in this example), check for a valid, live connection and finally, print out the IP address.


>>> import network
>>> sta_if = network.WLAN(network.STA_IF)
>>> sta_if.active(True)
True
>>> sta_if.scan()
[(b'BigHouse', b'0Z:\xc7\x82\x10', 6, -67, 32, False)]
>>> sta_if.connect("BigHouse", "Th3Pa55word")
>>> sta_if.isconnected()
True
print("Connected, ip is: " + sta_if.ifconfig()[0])
Connected, ip is: 192.168.4.3


Tip #7  — Create an access-point on the W600  …and then shut it down again.  First we need to load the easyw600 module, which contains Winner Micro’s own helper functions to make this easy.  There’s just a single call to easyw600.createap(), with your choice of SSID.  You’ll find that the  new access point pops up immediately and is visible and accessible (but not very useful) from any nearby device equipped with WiFi:-

>>> import easyw600
>>> easyw600.createap(ssid="W600_softAP")
softap working, ip is 192.168.43.1

When you’re finished, there’s just a single call to easyw600.closeap() to shut it all down again:-

>>> easyw600.closeap()


Tip #8  –  Enable an FTP server process.  This will allow us to manipulate files on the W600, so that longer MicroPython programs can be written elsewhere and then debugged on the device itself.   Before you start with the FTP server, you need to make sure that your W600 is already on-line and associated with an existing AP (see tip #6, above).

The FTP server is included in yet another module, this time named simply “w600”, so to begin with, we need to make sure that it is imported.  After that, there’s just a one line command to start the FTP server with a given username and password (note that in the given example, the username and password are both set literally to the word “None”):-

>>> import w600
>>> w600.run_ftpserver(port=21,username="None",password="None")
ftpserver is running.

[After writing this tip, I found that the “easyw600” module has a wrapper for run_ftpserver() which is even easier to use, just:-  “easyw600.ftpserver()” ]

You can now access your W600 from any local machine and you’ll see something like this:-

Connected to 192.168.4.3.
220-= welcome on W600 FTP server =-
220
Name (192.168.4.3:guest): None
331 Password required for None
Password:
230 User logged in
Remote system type is UNIX.
ftp> ls
200 Port Command Successful.
150 Opening Binary mode connection for file list.
drwxrwxrwx 0 root root 0 Jan 1 2018 sys
drwxrwxrwx 0 root root 0 Jan 1 2018 lib
drwxrwxrwx 0 root root 0 Jan 1 2018 cert
-rwxrwxrwx 0 root root 139 Jan 1 2018 boot.py
-rwxrwxrwx 0 root root 34 Jan 1 2018 main.py
-rwxrwxrwx 0 root root 40 Jan 1 2018 easyw600.py
226 Transfert Complete.
ftp>

So, we can now create a file, “fc.py” containing Python code on our local Linux machine:-

def wibble(FC="dog"):
    print("Furry creature: " + FC)

wibble("cat")
wibble()
wibble("ferret")

Now upload it to the W600 using FTP’s “put” command and then go back to the W600 console and type:-

>>> import fc

…(note:- there’s no “.py” on the end) and you’ll see the output from your new code.

If you repeat the “import fc” command, there’s no further output, but you can now call the “wibble” function from the REPL command line.  Try:-

>>> fc.wibble()

and

>>> fc.wibble("rabbit")

Note that it isn’t really possible to un-import a file (or module) once it has been cached, so -don’t- edit your file remotely and then expect to see the changes reflected when it is re-uploaded. MicroPython generally ignores an import request for something which it already has marked as existing in cache. The only bullet-proof way around this is to reboot the W600.


Tip #9  –  How do I reboot the W600 (without pulling the power cord)?

>>> import machine
>>> machine.reset()

Tip #10 – And finally, here’s a replacement main.py file which you can now upload to your W600 to have it automatically connect to your WiFi network and start the FTP server (both as described above) on reboot. You -will- need to set the SSID and password for your access point before installing it.

##
## main.py file content. Used to automatically start
## the network, join an access-point and then start
## an FTP server on the W600 at initial boot.
##
## *** You must set an SSID and password ***
##
import network
import w600
import time

print(“Starting network and FTP server…”)

##
## Join Existing Access-Point (Local Wireless Network).
##
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.scan()
sta_if.connect(“MY_SSID”, “MY_PASSWORD”)

##
## Start built-in FTP Server.
##
w600.run_ftpserver(port=21,username=”None”,password=”None”)

##
## …and let the user know what our address is.
##
print(“Waiting for DHCP…”)
time.sleep(5)
sta_if.isconnected()
print(“Connected, ip is: ” + sta_if.ifconfig()[0])


 

Single button remote control for TASMOTA

This is just a quick reiteration of a simple project from 2016 to show how easy it is to use an ESP8266 to solve a real-world problem.

Our television is quite a few years old now and still working well, apart from one annoying problem; it no longer recognizes the on/off command from any of the 3 compatible remote controls that we have.  To get around this problem, I popped an ESP8266 into a junction box between the TV and the mains socket, loaded it up with TASMOTA (of course) and then used IFTTT.com to connect our Googly Home Mini back to the ESP.  Now we can just say “Hey Gew Gull, T.V. on!” and everything works like a charm …well, mostly.  My better half mumbles quite a lot (it’s usually “Rhubarb, rhubarb …humbug …seat down”, or something along those lines), but both Goojle and I agree that she does mumble …and it doesn’t seem to matter whether it’s in English or Japanese.  This is a problem, because while I’m always willing to walk across the room to turn a television off, I’m somewhat reluctant to turn the da$”!@ thing back on (and if you have ever been subject to the brain-rotting onslaught of puerile slop served up on Japanese TV, you’ll know what I mean).  The whole point of the ESP was to fix it for her.

However, reading about all the latest and greatest microcontroller stuff over on CNX Software the other morning (over breakfast, while she was partaking of the aforementioned BRooPS),  I came across an article on a low-power LoRa-based dual switch unit, which reminded me strongly of the old 2016 ESP doorbell project. MOSFET power-latch schematic I suddenly realized that I not only had the answer to mumbling (no, not a gag  …don’t be cruel!), but I also had the hardware already built and sitting (somewhere fairly well down) in the “previous-projects” box.

With a television, radio and most lights, you already know the status of that device (whether it is on or off) and the issue is that you want to change that status (think of those light switches at the top and bottom of a flight of stairs …you don’t really notice whether the switch is currently up or down …you just know that in the middle of the night you need to flick the switch at the top to see your way down and then flick the one at the bottom to turn the light off again).  You just want to toggle the state.  One thing that we do know about TASMOTA is that it does “toggle” really well.  So basically, all we need to do is tweak the doorbell demo just a tiny bit to send the MQTT data to a different topic and with a payload of “TOGGLE”.  That shouldn’t be too difficult.

And it wasn’t.  I still had a ton of superfluous crud in the demo code to flash and fade the multitudinous LEDs on the Yellow Dev Board from the previous project, but I just left it in there (along with the OTA update functionality).  The main changes were to add the new topic:-

TV-Switch/cmnd/Power

and add a static payload:-

TOGGLE

Oh, and because I wanted the ESP to stay connected long enough to grab any OTA updates that I might be trying to fling at it, I extended the run time to a whopping 12 seconds and added a boolean flag to prevent the main loop from toggling the power to the TV 11,500 times while we were waiting for the OTA timeout.

The tl;dr summary of the doorbell hardware is that a single tact switch provides a pulse of power to the ESP8266, which is enough to bring it up to the state where it can turn on a MOSFET attached to GPIO16, which is connected directly across the tact switch and so latches the power to the ESP on, even when you remove your finger from the switch.  Once the ESP has connected to local WiFi, sent off its packet to the MQTT broker and handled any pending OTA update (or, most likely, timed out) it simply removes drive from the MOSFET gate, turning it off and thus powering itself down.  There is no “standby” current draw, as the whole unit is powered down.

One-button-remote in operation

All done and dusted in time for her birthday, neybothaman!

 

 

ESP32 + W5500 — Simple Working Example

Update June 2019  —  A couple of people have mentioned (both here and on GitHub) that they are having difficulty compiling the code for this project, with “invalid abstract return type” errors.  This turns out to be an upstream problem caused by a non-backward compatible modification of the Espressif  arduino/ESP32 library.   You can force the build to use an older (compatible) version of the library by changing a single line in your platformio.ini file:-

—  platform = espressif32
++  platform = espressif32@1.6.0

Thanks to @maniekQ for documenting this workaround.


Over the past couple of days, in the course of answering questions on the popular article on adding an ethernet port to the ESP8266, I found myself putting up a link to some new code for a work-in-progress project which simply replaces the ESP8266 with an ESP32 (which seems to make a lot of sense, given the falling cost of the ESP32 modules, nowadays).  ESP32 + W5500 moduleWhile that project is for an ESP-Now gateway, it seemed like there was a need for a nice, simple test and verify project where people can do a minimum of work with the hardware (an ESP32, a W5500 module, some jumper leads and a breadboard) and get a working result in a reasonably short time.  I’d said in various places that it shouldn’t take too much work to modify the code for the ESP-Now project to handle any of the examples shipped by default with the Arduino Ethernet library, so that’s what I’ve done.

Here’s the code (along with the pinouts in the README) for the simple “UdpNtpClient” example, munged very slightly to work with the ESP32Output exampleAll it does is connect to an NTP server, retrieve the current timestamp and display the UTC time.  This is basically a 30-minute project to produce a working demostration of an ESP32 using hard-wired Ethernet.

The configuration uses a static IP and network setup (router/gateway, netmask and DNS), as the original ESP8266 project seemed to have problems with DHCP (and quite honestly, I just haven’t gotten around to trying it with the ESP32 version, yet …let me know how it goes if you do).  All of the configuration options are in the “local_config.h” file.

The original library example code uses a single NTP server, “time.nist.gov”, which seemed a little anti-social to me, so I’ve added several of the more popular geographical pools into the config file and updated the default target to be the main “pool.ntp.org”.   You should choose the one closest to you (unless you’d like to see how unreliable bare UDP really is, in which case you might like to try “antarctica.pool.ntp.org”  —  apologies if you’re reading this from McMurdo Station 🙂 ).

 

 

Recent Updates (March 1st, 2019)

Otto Winter has been continuing his updates to esphome with improvements to the set-up wizard and the addition of min/max settings for rotary encoders (esphome enables you to add an ESP8266 or ESP32 to Home Assistant without writing any code).

Theo Arends has been working on reducing stack space usage in Sonoff-TASMOTA to fix some intermittent crashes.  If you’re having issues, please upgrade to version 6.4.1.18 or greater (see this post for more details).

Phil Bowles has been updating the API documentation and examples for his esparto rapid development framework for the ESP8266 (available as an Arduino IDE library; write concise, working code with no setup() or loop() functions).

Xose Pérez has made lots of changes to his espurna replacement firmware for ESP8266 devices over the past few weeks, with support for more than twenty new products added and the incorporation of many fixes (both from Xose himself and submitted by an ever-growing community of users).

Rich Heslip has published an ESP32 project, “Motivation Radio BLEMIDI”, to add WiFi and Bluetooth functionality to Eurorack based modular synthesizers.  The hardware for this module is also open source and available from a separate repository, courtesy of Jim Matheson.