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

Advertisements

One thought on “ESP8266 Lua Timer on a Tight Budget

  1. With the latest update to Lua, the IP address is no longer needed – and the code works reliably – except… it won’t work in a file – only when run stand alone – out of the frying pan and into the fire as we say in the UK. I’m sure it’s just me…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s