Simple Accelerometer Data Conversion to Degrees

Here is a handy lua Corona Labs code chunk to convert xyz accelerometer data to degrees.

I am building an augmented reality app that needs to know when the user tilts and rolls a phone around so it can update the user interface with augmented reality elements. Corona already has the accelerometer acquisition code but now I want to display this data in human readable degrees (e.g if you were looking half way up the sky you would expect 45° and the horizon 0°)

A shout out goes to Doug McFarland here for the original c/Arduino code (http://wizmoz.blogspot.com.au/2013/01/simple-accelerometer-data-conversion-to.html) that I converted to Lua.

Code:

            --Input Data
            local xAxisData = --insert xaxis sensor data here
            local yAxisData = --insert yaxis sensor data here
            local zAxisData = --insert zaxis sensor data here
            --Convert raw 0.0 ~ 1.0 sensor datad to degrees.
            local xAngle = math.atan(tonumber(xAxisData) / (math.sqrt((tonumber(yAxisData) * tonumber(yAxisData))) + (tonumber(zAxisData) * tonumber(zAxisData))))
            local yAngle = math.atan(tonumber(yAxisData) / (math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) +  (tonumber(zAxisData) * tonumber(zAxisData)))))
            local zAngle = math.atan(math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) + (tonumber(yAxisData) * tonumber(yAxisData))) / tonumber(zAxisData));
            xAngle = xAngle * 180.00
            yAngle = yAngle * 180.00
            zAngle = zAngle * 180.00
            xAngle = xAngle / 3.141592
            yAngle = yAngle / 3.141592
            zAngle = zAngle / 3.141592
            --Round down a bit and display
            print("X Degrees: " .. tostring( math.round(xAngle,1)) .. " (Original X: " .. tonumber(xAxisData) .. ")")
            print("Y Degrees: " .. tostring( math.round(yAngle,1)) .. " (Original Y: " .. tonumber(yAxisData) .. ")")
            print("Z Degrees: " .. tostring( math.round(zAngle,1)) .. " (Original Z: " .. tonumber(zAxisData) .. ")")

Output Data:

    Accelerometer X Data: -0.0264 = -1&deg
    Accelerometer Y Data: -68 = -68&deg
    Accelerometer Z Data: 0.3682 = 68&deg

Comments:

This does not look too handy to some but this is gold in plotting the horizon and calculating far away objects with trigonometry.

Don’t forget to detect what orientation the mobile device is in (portrait, landscape, upside down portrait and upside down landscape). You will need to factor these display modes into the calculation before converting to degrees. Sometimes it is easier to just develop portrait or landscape apps (not both).