ESP8266 LUA and MQTT

After a few days break wherein work got in the way of interests (not a good thing) I got up early this morning, determined to do some work on my ESP-01 boards while I have a clear weekend ahead of me. I checked for updates for MQTT and there are none – which is fine – that indicates that nothing has gone wrong this week.

On a whim I decided to go check the LUA site. I already new that the latest MQTT had been imported from conversations with Minh  who’s been doing the MQTT work but I was delighted to see signs that also some more work had been done on integration with Eclipse.

Every single time I’ve tried to install the nodemcu LUA code into Eclipse there has been a problem – something not found, some path missing, some issue taking hours to resolve.

Yet this morning I downloaded the latest ZIP file (updated yesterday) and imported it into Eclipse. CLEAN – COMPILE – FLASH…  not a hiccup – it worked perfectly. Not only that but when I tried powering Lua up – it came up straight away without any hint of an issue. This is new for me as I’ve always had some trouble or other. Magic.

Though it is possible to debug Lua code using the simple terminal you can install into the Eclipse environment, I did develop my own serial terminal  and then subsequently discovered ESPLorer.

I powered up ESPlorer and checked the available RAM on my newly installed Lua installation on an ESP-01 (I’m still waiting for my new white board to turn up from China with all the pins available – meanwhile I have ESP-01, ESP-03 and ESP-12 boards to play with).

A quick node.heap() call showed that we’re starting off with 22,144 bytes of working RAM which is a good improvement on the earlier versions especially as MQTT is now incorporated.

First things first, I told the unit about my router and then my MQTT broker which regular readers will know is sitting on a Synology DiskStation and has been sitting there working flawlessly for weeks now despite my attempts to bombard it to death with messages.

I noted when using wifi.sta.getip() that the unit remembered my router from previous experiments (I wish someone would produce a nice graphical memory map to show where these various elements are stored and how to tinker with them). So that was easy.

I followed this example – obviously filling in the bits that apply to my installation..

— init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")

— setup Last Will and Testament (optional)
— Broker will publish a message with qos = 0, retain = 0, data = "offline"
— to topic "/lwt" if client don’t send keepalive packet
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)

— on publish message receive event
m:on("message", function(conn, topic, data)
  print(topic .. ":" )
  if data ~= nil then
    print(data)
  end
end)

— for secure: m:connect("192.168.11.118", 1880, 1)
m:connect("192.168.11.118", 1880, 0, function(conn) print("connected") end)

— subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)

— publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(conn) print("sent") end)

m:close();
— you can call m:connect again

(again ignore the IP address and port – I filled in my own) – I ran this and… connected no problem. All seemed well.   I had subscribed to “test” rather than “/topic” and had commented out the publish for now.

I tried publishing “test” to see what would happen – nothing. But then I guessed as the last line was “m:close()” I figured it reasonable that the ESP-01 would not be listening and so called the connect line again – after all – there is a comment in there “you can call m:connect again”.

The result (passwords have been changed to protect the innocent):

> m = mqtt.Client("peteluatestid", 120, "xxxxxx", "yyyyyyy")

NodeMCU 0.9.5 build 20150123  powered by Lua 5.1.4
lua: cannot open init.lua
>

Yes that’s a crash. Oh dear, this is not the first time I’ve seen Lua just die. I can handle error messages but this tendency to just simply reboot…

Meanwhile, my experiments with programming in C, using MQTT directly have, thanks to Minh Tuan’s constant vigilance in fixing things, produced rock-solid results. Indeed I’ve been away since last weekend and I turned off a perfectly working MQTT temperature sensor in order to give Lua another go. I thought the one-wire library in Lua might make the transition to a Dallas DS18B20 a little easier but I’m not going to start another round of failed experiments while Lua so easily crashes.

Incidentally, I had several attempts with this Lua installation – rebooting several times along the way. When I finally managed to get the whole thing to work and in commenting out the CLOSE – as you need the connection open to receive anything, I noted my wonderful 22k of RAM had dropped down to 17.2K.  I really do wish they’d put a little more RAM on that chip.

Having checked that the compilation had included all the modules (app/include/user_config.h) which as far as I can tell the default combination SHOULD do… I thought I’d try the DS18B20 module – the idea being to send an MQTT request – and get an MQTT message back with the temperature in it.

I thought I would avoid experiment and merely check the temperature first.  I duly attached a working SD18B20 unit and pull up resistor to GPIO2 (that’s input 4 according to the table).

The code looked simple enough..

t=require("ds18b20")
t.setup(4)
addrs=t.addrs()   
print(t.read(nil,t.C))
t = nil
ds18b20 = nil
package.loaded["ds18b20"]=nil 

But no..

> t=require("ds18b20")
stdin:1: module ‘ds18b20’ not found:
    no field package.preload[‘ds18b20’]
    no file ‘ds18b20.lua’
    no file ‘ds18b20.lc’

Oh dear….

Thoughts? Am I missing the point here?

ESP8266 and RB Serial LEDS

rgb ledsWell, it looks like everyone and their auntie have figured out how to get Arduinos to listen to ESP8266s sending out messages and control RGB serial LED strips – not surprising as there are several Arduino (and for other boards) serial libraries out there. I’m not talking about old fashioned 12v RGB strip but the more modern 5v variety with serial control, which, when (if) they get the price down, HAS to be the future of lighting.

I was at a hotel in Blackpool a few weeks ago and they’d just modernised and had the serial LED strip EVERYWHERE. If you’re not familiar with this stuff, each LED has a serial controller and can accept RGB settings – and once set can simply pass the info to the next LED. All of this is done with blindingly fast serial, so fast they build huge TV displays at airports using the stuff. Why is this stuff so much better than the old PWM red then green then blue LEDS? Because all 3 chips are in one housing you can create REALLY subtle lighting – you want daylight? No problem Tungsten? No problem? Nice warm candle-light? No problem.

Grab a strip, fasten it to an Arduino, provide plenty of 5v and a library and you’re up and running. You tell the library how many LEDS you have and it builds an array of 3 bytes for each LED. You populate the RGB info for the LEDS, call a function and BANG – they all get updated in an instant. with that array at hand it is trivial to write code to drive a colour wheel through it and by updating at regular intervals, create a moving colour change along the strip that is nothing short of stunning.

Right – that’s the easy way and also the larger and more expensive way. Now when is some clever person going to provide us with the same library (in C, not Lua please) for the ESP8266. Should not be a problem as the chip is way faster than an Arduino. I am not familiar enough with the chip to do this yet but I’m hoping someone else is – or has already done this – any takers?

Add this to the current MQTT code and you have an instant WIFI lighting controller. If antone has this or can make this I’m quite happy to put an article together – once I have my hands on a library (preferably working with GPIO0 or GPIO2 on the ESP-01 as that’s the cheapest and smallest solution out there but is pin-challenged).. it’ll take me no time to get that under message control.

Eclipse and Node_MCU on Windows

Does anyone know what I’m doing wrong here… I have the full Eclipse set up on my Windows PC and have already imported the MQTT project and tested it – lovely. Like other projects you end up with CLEAN, ALL and FLASH controls to wipe old firmware binaries, compile new code and FLASH the ESP8266 modules – all very civilised and easy to use.    I did exactly the same installation with the node_mcu (ie LUA) software – and… nothing – no apparent way to do any of this within the Eclipse environment. Did I do something really stupid here? Hopefully, getting a solution in here will help others as well. Everything was installed from scratch on my laptop this morning so there is no old code here. It is all the latest downloads – and until Lua all went splendidly smoothly following instructions I’ve referred to in earlier blogs.

Examples – AT code – works fine.

AT Code

Example – MQTT project imported – works fine

image

See MQTT above – straightforward installation – the 3 buttons ALL, CLEAN and FLASH appear just like the other projects… but in the case of NODE_MCU….

image

Oh dear.- no buttons!

Also – if someone knows how to rectify this.. they might also be able to answer another question. Somewhere in the above project – I guess in the INCLUDE folder – is the 0.9.5 SDK.  In the other examples in ECLIPSE the best we have is the 0.9.4 SDK.  So, for example, what would one need to copy across, into a copy of the AT example from the nodemcu-firmware example, to be then able to compile the AT example with 0.9.5 SDK?

Any easy tips/answers in there I suspect will help a lot of people as well as myself. I could find all of this out with a lot of wasted time and experimenting, I’m hoping someone has done all of this.

ESP8266 Tuesday Update

esp-03[7]I noted this item on EBAY showing the ESP-03 at well under £2 each.. Not sure about those ceramic antenna – anyone any experience of how they compare to the excellent PCB version on the ESP-01 ??

Another item of note – I see there is a new LUA update out – looking forward to checking that out at the weekend and I’ll do a write up – apparently it’s based on the 0.9.5 version of the SDK. Is this out of BETA – and if it is does anyone have the link? And any updated documentation so we know what’s changed? I have to say that Espressif don’t do the best job when it comes to promoting their own updates.

That’s it for now – later this week I plan to put together a temperature sensor using only the ESP-01 and even consider sticking a lithium and a solar cell on it (I know, not the best time of the year for solar power) – more to have a permanent test rig than anything else sending out MQTT data.  The /TIME/ message I set to run every 10 seconds on my PC 3 days ago using Really Small Message Broker set up as a service, and MQTT-spy – is still ticking away (I can test it in meetings using another copy of MQTT-spy.   You might have noticed I did some frighteningly fast message blasting and everything help up ok. I expect soon to have MQTT traffic running back and forth – I’ve at least 3 locations that need external solar powered temperature and humidity monitoring.   MQTT-spy is due shortly to get some more improvements – looking forward to it – as for RSMB – I can’t think of anything wrong with it!

Feeling MQTT Thick

Oh firstly, after filling in the form with Espressif to keep commercial confidentiality about their SDK info which I’m still waiting for – I discover it’s freely available here – http://www.esp8266.com/viewtopic.php?f=5&t=449  granted that IS for the 0.9.2 version which is a tad old now..

Tonight as I get ready for a round of meetings in London which will severely hamper my research until later this week, I’m struggling with MQTT-SPY. I should say I’ve had some communication with the designer and he’s been MORE than helpful  – he’s added a demo time script, he’s changed the XML format slightly so it’s readable for the likes of Notepad++ all of which is great, but I want some pre-programmed scripts to send out publications – and can I HELL figure out how to use them.  I’m hoping for an update to the WIKI on that otherwise excellent free program. If nothing else I hope to set off a script every minute to transmit the time on “/time” and I can keep an eye on it while I’m away on business to check for reliability.

I didn’t get a chance today to update the ESP-12, now that the MQTT code works so well in the Windows environment, to add port operations to that as I thought I might use a couple of pins of the board as indicators instead of all that serial info. All I want coming out of the serial is MQTT messages.

My unashamedly Windows-only ESP8266 Facebook page  is doing well and how has over 170 followers which is nice.

Not much else is new. Quite interesting that people made so much noise about the Lua interpreter code going open source – the guys did that and what’s happening? Not  a lot right now.. the Frankenstein code? Nothing for a month….   the beta of the SDK? Nothing new.  Maybe everyone’s having the week off after Christmas.

Here’s hoping for lots of new developments over the weekend. Something I don’t really understand about the Lua code – it’s constantly short of RAM – and yet, those who are trying to understand the chip say that it has a LOT more DRAM than it has RAM… so I wonder if any of that is being used.. perhaps that will remain one of life’s mysteries.

And on a completely unrelated subject – if you’ve been struggling with your old Nexus 7 (2012) – the 5.01 Android update is out -  installed it today (with a lot of wheel-re-inventing) – and.. yes, I think it speeds it up again.

The Simple Serial Terminal revisited

My prototype ESP-03 board“Got up early one morning….”  well, actually it was one evening a couple of week ago, I was frantically struggling to use the Arduino serial monitor to test the new ESP-01 modules (which appear to have had babies, they’re all over the place now) and not getting very far, one line at a time, repeating the same typing mistakes over and over…  and I decided I needed something better. Windows programming is not something I’ve done for a while (as against web and App programming). The last time I wrote anything major was back in the dark ages of VB6 and so I was expecting to fail completely with Visual Studio though I use it a lot for embedded C programming, desktop apps are another matter.  I managed to find some code to take data from the serial port, put it up on screen and vice-versa and the funny thing is it all started coming back to me. The project that was going to take me the drinking time of a cup of coffee took all night and I was so happy with it I stuck a copy on the web. I have to say version 0.1 looked pretty naff.

Scargill's Serial TerminalBack to programming the pesky ESP8266 chips and once again I found myself getting more and more frustrated. I needed places to store things temporarily, I got annoyed when as happened one night, the power went off mid-stream and I lost all my temporary notes and… well, if you’ve worked on these chips, having to discover the bugs as you go along and repeating the same stuff with minor variations until you got there, you’ll know exactly how I feel. On top of that, the interpreter hates you sending stuff quickly and whenever I looked it up on the web I kept getting recommended to use some Linux program or other – sorry guys.. NO.

Fast forward to this morning where I realised just what an amazing little tool I’d put together with a few late nights behind me (and I mean LATE). Now, before I say any more, apologies to anyone on Windows XP – I can’t help here because the Microsoft environment really isn’t supporting XP any more – it’s not me, the code  just won’t work on XP. As for the Linux guys, well, you’ve probably got your own tools and they’ll be far better so I’m not worried about you so this is for Windows 7 and upwards.

So specific needs when messing with these chips – and especially when using the Lua interpreter – you need to be able to send blocks of code to the chip over and over as your program evolves and you need to be able to store temporary solutions, lots of them. The Lua interpreter has a strange file system that means when creating a file you need to wrap your code in the most horrible mess which makes it almost unreadable – just what you don’t need when bugs creep in. You need delays between each line you send, maybe up to half a second as the interpreter does not like being sent serial data when it’s busy. You also need to be able to blow firmware onto the boards but I haven’t gotten that far yet and anyway there are some decent Windows tools out there to do just that.

And so here we are two weeks later – I have the tool I need to do the job and I realise I’ve done a pretty awful job of documentation. So above right you should see the editor. The most important bits are the two big windows – on the left is the area you type in – multi line – and on the right is the output from the serial line – i.e. what comes back from the chip. In the simplest case you set up the serial port you want, ensure it’s set to 9600 baud, select “serial – open” and you’re all set (I’m assuming you have an FTDI or similar on your USB lead, talking to the serial on the ESP8266 device, I’m also assuming you fed 3v3 to the device and are using some means of ensuring the device never gets hit with anything above 3v3).

Whatever you type in the left window is non-volatile, i.e. it’ll still be there after you blow up your serial port and have to reboot the computer.

Disclaimer: if any of the above or the use of the terminal breaks your computer, it’s not my fault. I’m providing this freely just because I’ve no reason not to but without support.

The top panel

So let’s take a look at the top first. I have deliberately kept this as clean and simple looking as possible as you really just want to get on with coding and not worry about some pesky program – but there are some basics if you want to make good use of this. The file system is easy enough – you might want to store what’s in your left window – your latest all-singing routine or just a bunch of nonsense – that’s up to you hence file – save. Find a suitable directory to store your stuff – the dialog is bog-standard. For retrieval – you have two options, load and append. The former will overwrite what’s in the window, the latter will append to what’s there – so you can store a load of routines and build up something new the easy way.

NotepadSerial is even simpler – open or close the port. When open you’ll find some controls don’t work – like changing the baud rate for example.

Notepad is interesting…yes, no less than 10 pretty coloured notepads (non-volatile) to store snippets in – nothing clever about these, you can just copy and paste to and from them in the normal way.

I normally have several projects going on and find it handy to have stuff lying around – this beats yellow sticky notes full of code any day. There’s a big HIDE button at the bottom to get rid of these – and don’t be fooled by access to the ribbon when Notepad is open – it’s disabled.

NotepadClear- well you can clear the notepads or your left or right windows – and help – well it’s a picture of me – the idea of writing a complete help system for this just filled me with horror.

So down at the BOTTOM of the screen… assuming you have the serial all turned on you can “Send Window” – i.e. send the contents of your left window off to the serial port – it will send it one line at a time with a delay between each line specified at the top right in milliseconds, defaulting to 400ms – but whatever works for you. 

I’ve coloured the individual panels just to try to help for when you’re in a hurry – I tried to colour the tabs but Microsoft isn’t having any of it up to now.

If you select some text in the normal way in that left panel you can press the “Send Selected” button and only send the stuff that is highlighted – OR you can “copy” from just about anywhere and send whatever is in your clipboard… that’s awfully handy. 

The bottom panelThen there are those notes.. N1 to 10 let you send the entire contents of any of those notepads.  Finally there is a one-line window which you can send directly with the “Direct” button and that has autocomplete for some of the more useful commands.

To the right there are some presets, 6 in all – and in SETTINGS you can define their names and what gets sent out.  And that takes us to settings.

Settings

Firstly you’ll see the 6 preset buttons – their titles and contents – note you DO have to press OK to save these – most things outside of this SETTINGS box just save automatically. Auto prefix and suffix I suggest you leave be unless you’re NOT messing with Lua and the “Auto prefix/Suffix” tickbox determines whether or not you use this – essentially if “File.open” is see starting at the LEFTMOST character in your input window, these prefix/suffix characters will be added to your line as they are being sent out until the system sees a “File.close” again starting in the leftmost column of your input window.

“Arduino DTR” – well that’s for those of you who want to use this terminal with your Arduinos (you may be working with the Espressif AT firmware for example)  – that’s the bit that resets them when you open the port. It just flicks the DTR line temporarily on open – nothing more. Autoclear – tick that and you’ll see the right window cleared every time you press the send button – just preference really. Lua comment removal is turned on by default (—) – you can turned if off – and “Retain blank lines” is new, just something for the future. Normally, most blank lines never make it to the right window.

And that is that, really – nothing much else to tell you about the program – I hope you find it useful – I have – and no doubt I’ll add more in time.

Oh apologies to the guys who now find the Lua interpreter returns NIL when empty… I think that was my idea. I keep firing stuff off to Zeroday who is doing a cracking job on what can’t be a trivial project.

Oh here’s the dropbox link – not sure how long this will stay valid but you can always let me know if it disappears.

Note: If you’re interested in what I’m doing here… join my millions of followers on the ESP8266 Facebook page (actually it was 41 at last count) https://www.facebook.com/esp8266wifi or check me out on Google+ https://plus.google.com/+PeterScargill  if Twitter is your thing… https://twitter.com/scargill erm, what else.. oh yes www.scargill.net or www.bedrock.es or www.hollyberry-cottage.co.uk … I think that’s about it.

ESP8266 Lua Timer on a Tight Budget

My first attempt to fire something back for the help I’ve had from others, firstly to get past the bottleneck of understanding the ESP8266 boards and secondly the firmware options – in this case I’m assuming you are interested in the Lua firmware. I’m going to give the slight advantage here (for a change) to Windows users. The reason for that is simple – that’s what I’m using. I’ve developed a serial terminal for people like me to play with when tackling Lua.  I’ve spent the better part of a couple of weeks to get to this point.

Go here to get the firmware developed by Zeroday and check out his documentation here.  You will also most likely need the flasher from here. In a subfolder of the firmware directory (you will download a ZIP file) you’ll find a file called nodemcu_512k.bin – that’s it, just the one file. You can load that up, set your serial terminal to 9600 baud. If you want a serial terminal for Windows 7 upwards with no warranty or support but likely the best tool for the job you can grab my installation zip here. If that link doesn’t work, let me know. Why do I claim it’s the best? Because I tried all the rest and for this particular application they were lacking – so I built my own.

Once you are up and running with whatever tools, you’ll want to test the firmware. Simply try this..

print(“Hello”)

If that works, its up and running (don’t forget to ground GPIO_00 when programming the firmware and then remove it and cycle the power before trying to use it). I’ve had success with the ESP-03 module but if you can’t manage the small soldering the ESP-01 is better. I understand the ESP-12 has more pins and 0.1” spacing but I’ve not tried it yet.

You’ll want to use it for something – so here’s a start. I’m going to assume you have access to a PHP server somewhere… 

Load that up onto your site and call the program – whatever you call it – let’s call it time123456.php – note I’ve referred to this in the code but call it whatever you like, really.

you’ll get the following back:

{time=1418272378;timestr=04:32:58 11-12-2014;dawn=07:38;dusk=16:24;}
 

I built this for my own private purposes – there is some command line info you can add for different areas, this returns info for the UK. As you can see it returns the time in a standard format and also as text. It also returns dawn and dusk times for the same location.

Why did I do this – I found that time servers could be slow and didn’t give me what I wanted – so I built this. Here is the PHP code. I don’t pretend to be a PHP master – it’s all just standard stuff. You can dump this on pretty much any PHP site you may have FTP access to.

<?php
$locn=”Europe/London”;
$lon=55;
$lat=-2;
date_default_timezone_set($locn);
if ($_GET[‘loc’]!=””) $locn= $_GET[‘loc’];
if ($_GET[‘lat’]!=””) $lat= $_GET[‘lat’];
if ($_GET[‘lon’]!=””) $lon= $_GET[‘lon’];
$dateTimeZoneLocal = new DateTimeZone($locn);
$dateTimeLocal = new DateTime(“now”, $dateTimeZoneLocal);
$localDateTime = date(“H:i:s d-m-Y”, time());
$localTime=strtotime($localDateTime);
echo “{time=”.$localTime;
echo “;timestr=”.$localDateTime;
$sun_info = date_sun_info($localTime, $lon, $lat);
foreach ($sun_info as $key => $val) {
    if ($key==’civil_twilight_end’) echo “;dusk=”.date(“H:i”, $val);
    if ($key==’civil_twilight_begin’) echo “;dawn=”.date(“H:i”, $val);
}
echo “;}”;
?>

If that’s obvious – make use of it, if not, just use mine.

Anyway so now one way or another you have the ability to get the time.

This little program for Lua does a couple of things – it goes to the site and gets the time.  Why do I use an IP address as well as the website address? Because I can’t get the Lua Name lookup code to work reliably – I’ve contacted Zeroday and when that is ultra-reliable we can forget IP addresses. For now it’s a necessary evil.

— Globals needed for clock – IP needed until DNS is more reliable
second=0 minute=0 hour=0 day=0 month=0 year=0
ipnr=”xxx.xxx.xx.xxx”
host=”www.yoursite.com”

file.remove(“getTime.lua”)
file.open(“getTime.lua”,”w”)
    conn=net.createConnection(net.TCP, 0)
    conn:on(“receive”, function(conn, payload)
                    hour,minute,second,day,month,year=string.match(payload,”.*timestr=(%d+):(%d+):(%d+) (%d+)-(%d+)-(%d+)”)
                    conn=nil
                     host=nil
                    ipnr=nil
    end )
    conn:connect(80,ipnr)
    conn:send(“GET /time123456.php HTTP/1.1\r\nHost: ” .. host .. “\r\n”
              ..”Connection: keep-alive\r\nAccept: */*\r\n\r\n”)

file.close()

tmr.alarm(1,1000, 1, function()
    second=second+1
    if second>=60 then
        second=0 minute=minute+1
        if minute>=60 then
            minute=0 hour=hour+1
            if hour>=24 then
                hour=0 day=day+1
                if day>=32 then day=0
                end
            end
        end
    end
print(string.format(“%02d:%02d:%02d %02d/%02d/%04d”,hour,minute,second,day,month,year))
end)
dofile(“getTime.lua”)

Before we start, you see the bits in bold – if you don’t use my terminal, you’ll need to wrap each of those lines in file.writeline([[  and ]])  so that they end up being written to Lua as a file.. the reason you want to do that a lot is to minimise the use of RAM. The reason you’d want to do that would fill a lot of space.

So essentially you are initialising some variables – you’ll need to put in your website address and IP address (IP lookup).  You are creating a FILE in Lua called getTime.lua – that file when called will go off and get the time from your server – and put it into the time and date variables – clearly without that they’ll start at zero.

The second part starts off a repeating timer (you now have 7 of them numbered 0-6) – which operates every second The operation is fairly obvious – every second in this case it will print out the time and date – note the  string formatter – handy to know about. So we initialise variables, create a file to go get the time, set up the timer then run the file.

In real life the local clock does not handle months and years etc, so I’d suggest setting up another timer or a means of doing that dofile(“getTime.lua”) on power up then once a day maybe after midnight.

So this of course is only a tiny component – you have plenty of FLASH (but not a lot of RAM).  You might set up some kind of timer to turn something on and off- see the Lua documentation – depending on which board you have, you might have 3 or 4 outputs – in my case (I’ve not strung all of these together yet) I can read temperature.  With a little mod you can have the program understand lighting up time and dawn time as well.

So now you have Internet controlled temperature monitoring, relay out and a real time clock with dusk and dawn ability.. if that doesn’t start your imagination going… well. And all for what, well under a tenner including Chinese power supply?

At a later time I’ll detail the other components of the larger project above. Check out my other stuff at https://scargill.wordpress.com , www.scargill.net and for Facebook users, https://www.facebook.com/esp8266wifi – this is just the beginning.

And that serial output that puts out the time – if you happen to have one of these handy Sparkfun Microview modules you could even make a clock! Ok, they’re not cheap. https://www.sparkfun.com/products/12923

ESP8266 Lua Real Time Clock

I nearly have this running – I could do with a little help though!

The latest LUA has more than one timer – so you can spare one for a clock.

Here’s the basic idea – you can run this as is if you want…

tmr.alarm(1,1000, 1, function()
second=second+1
if second>=60 then
second=0 minute=minute+1
if minute>=60 then
minute=0 hour=hour+1
if hour>=24 then
hour=0 day=day+1
if day>=7 then day=0
end
end
end
end
print(string.format(“%02d:%02d:%02d Day=%01d”,hour,minute,second,day))
end)

There you go – THAT was easy !!
It’s also quite easy to get the time from a server. I made my own PHP page and put it on any old hosting – I’ll not make that public or my server will get stoned to death but it doesn’t take much of an imagination to go get the time. In this example I’ve missed out month and year but you get the idea.  What I would do it get the time every night maybe 2am from a real clock (and on power up of course)

In my case from my web code,  I get a string back which contains….” lots of stuff ;timestr=22:04:02 10-12-2014; more stuff”

So – I want to extract at least 3 and more likely all 6 numbers out of there – so I can punch them into my variables above.  I can do it one at a time but it would be NEAT if Lua could return 6 variables at once… like….

hour,minute,second,day,month,year=string.match(string.match(payload,”timestr=%d*”),”%d*”)

Except of course that the last bit of that is rubbish because I’m rubbish at regular expressions – I don’t suppose any of you Lua masters out there would know how to take that string above and convert it into the numbers I want?  I promise if someone provides a working solution, I’llrepay by publishing the source of my PHP page – which actually returns a lot more in the string.

Why not figure out how to access an NTP server? I find them slow – this is instant and I get more useful info back.

Thoughts?

ESP8266 Lua Updates

Two new updates out – the actual LUA interpreter (grab the ZIP file – find the latest update in a directory) an the program for Windows to actually blow the chips – both 32 bit and 64 bit Windows.

Have fun – new feature on the Lua interpreter – 7 timers – that means you may need to update your code as there is now an extra parameter on the alarm call – first parameter – value 0-6

So we now have an updated LUA interpreter – and updated file to blow firmware and my latest editor update which simplifies the process of programming – and now – I’m working on my next blog – a complete, working and USEFUL app. I’ve had a complete re-think about how to handle this and have a stable app running – just needs a little R&D on file handling and I’ll be back in here – it will be worth the wait!!!