如何在JavaScript函数中计算传感器的方向?我在3d Accelerometer calculate the orientation中看到了示例,但不确定如何在计算中应用msg.payload.xAxis / yAxis / zAxis的值。如果可能,我需要以新字段的形式将其应用于以下示例有效负载。
{
"device":"368640",
"deviceType":"Sigfox-Tracker",
"version":3,
"timestamp":"1535121228",
"rssi":"-113.00",
"battery":3.28,
"temp":21.5,
"soil":2107,
"xAxis":61,
"yAxis":-26,
"zAxis":994
}
答案 0 :(得分:0)
您粘贴的是一个javascript对象,访问其属性的方法之一是使用dot notation,例如下面的data.xAxis
。
我创建了2个函数来根据您链接中的the answer进行计算。然后,我将内置的Math object用于所提供的公式。
这里是例子:
let data = {
"device": "368640",
"deviceType": "Sigfox-Tracker",
"version": 3,
"timestamp": "1535121228",
"rssi": "-113.00",
"battery": 3.28,
"temp": 21.5,
"soil": 2107,
"xAxis": 61,
"yAxis": -26,
"zAxis": 994
}
function calcRoll(y, z){
return Math.atan2(y, z) * 180/Math.PI;
}
function calcPitch(x, y, z){
return Math.atan2(-x, Math.sqrt(y*y + z*z)) * 180/Math.PI;
}
let dataX = data.xAxis;
let dataY = data.yAxis;
let dataZ = data.zAxis;
let roll = calcRoll(dataY, dataZ);
let pitch = calcPitch(dataX, dataY, dataZ);
console.log(`roll is: ${roll} and pitch is ${pitch}`);
答案 1 :(得分:0)
谢谢安德鲁,这是在msg.payload中采用的正确语法,因为每个有效载荷报告的值都不相同?
let data = msg.payload
function calcRoll(y, z){
return Math.atan2(y, z) * 180/Math.PI;
}
function calcPitch(x, y, z){
return Math.atan2(-x, Math.sqrt(y*y + z*z)) * 180/Math.PI;
}
let dataX = data.xAxis;
let dataY = data.yAxis;
let dataZ = data.zAxis;
let roll = calcRoll(dataY, dataZ);
let pitch = calcPitch(dataX, dataY, dataZ);
msg.payload.roll = roll;
msg.payload.pitch = pitch;
return msg;
这是当新修改的有效负载到达时我在Node-RED中查看的调试消息:
{"device":"368640","deviceType":"Sigfox-Tracker","version":3,"timestamp":"1535136195","rssi":"-109.00","battery":3.28,"temp":19.5,"soil":2105,"xAxis":71,"yAxis":-32,"zAxis":1002,"roll":-1.8291836314227448,"pitch":-4.05104777734416}