Post your best Lua script examples here

User avatar
By blavery
#69805 The NodeMCU Lua has inbuilt support for reading X and Y and Z acceleration values from the adxl345 accelerometer. It is also easy to get accelerometer values sent to the ESP8266 by Blynk from your phone. But often the useful information is not X,Y,Z raw values but rather derived pitch and roll values.

Using the analogy of an aircraft, consider X direction = out the right wing, Y direction = straight ahead, Z direction = upwards (ie, "ENU" notation). Nose down is negative pitch, nose up positive pitch. And left wing down is negative roll, left wing up positive roll.

The NodeMCU Lua math module has very limited functionality, only math.abs(), .ceil(), .floor(), .max(), .min(), .pow(), .random(), .randomseed(), .sqrt(), .huge and .pi. This is not enough to calculate pitch and roll easily.

But using the math.atan2() function included into E Suite
https://github.com/BLavery/esuite-lua
it becomes trivial. Using three accelerometer readings which we can call ax, ay, az, then roll and pitch are:

Code: Select allfunction roll(ax , az)
    return - math.floor(math.atan2(ax, az)/math.rad)
    -- in integer degrees
end

function pitch(ay , az)
    return math.floor(math.atan2(ay, az)/math.rad)
    -- in integer degrees
end

The short functions for atan() and atan2() can be lifted easily from the E Suite files.