Post your best Lua script examples here

User avatar
By blavery
#69806 Using Blynk, it is trivial to send to your ESP8266 your smartphone's GPS location.

Sometimes, however, raw coordinates are not a convenient form to understand the data. Here is a routine to compare two GPS locations, and to return the distance between them, and their compass bearing. The code is part of E Suite
https://github.com/BLavery/esuite-lua
but is worth showing in its own right.

Note that it uses the sin() cos() and atan2() functions in E Suite that are not in the math module of standard Lua binary build, but those are short and easy to extract from E Suite.

Code: Select allgps={ lat0=0, long0=0} 

function gps.Ref(lat, long)  -- in degrees
    -- set a reference home position
    gps.lat0=lat * math.rad
    gps.long0=long * math.rad
end

function gps.Distance(lat, long)  -- phone GPS data in degrees
    local lat1 = lat  * math.rad
    local long1 = long * math.rad
    local R = 6371 -- Radius of the earth in km
    local dLat = lat1-gps.lat0
    local dLon = long1-gps.long0
    local a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(gps.lat0) * math.cos(lat1) * math.sin(dLon/2) * math.sin(dLon/2)
    local c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))

    local direc  = math.atan2(math.sin(dLon)*math.cos(lat1), math.cos(gps.lat0)*math.sin(lat1)-math.sin(gps.lat0)*math.cos(lat1)*math.cos(dLon))

    return R*c, ((direc / math.rad) + 360) % 360  -- km, degrees
end