You should not change the bytesToFloat
function; that function does not need to know how your payload is formatted (except if you change MSB/LSB), but just wants 4 bytes for its input. So, simply use the original bytesToFloat
along with:
// Test with 0213343F4A6666D2414C00D207424DB750C247 for 26.299999237060547
// outputted with one decimal as 26.3:
return {
sensorID: bytes[4],
// Take bytes 5 to 9 (not including), convert to float, convert to a
// string with one decimal, and use the unary plus-operator to cast
// the string result of toFixed to a proper number:
temp: +bytesToFloat(bytes.slice(5, 9)).toFixed(1)
};
Alternatively, showing why bytesToFloat
should not be adjusted to a specific sensor, but can be used for multiple values, assuming those are floats too, and using the x++
postfixed increment operator to keep track of the bytes that have been handled:
// Decode all, for readable code.
// Just assuming some encoding here!
// Skip bytes 0 and 1
var b = 2;
var batt = (bytes[b++]<<8 | bytes[b++]) / 1000;
var tempId = bytes[b++];
var temp = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);
var humiId = bytes[b++];
var humi = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);
var pressId = bytes[b++];
var press = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);
// Only return the values we're interested in:
return {
batt: batt,
sensorID: tempId,
temp: temp
};
Of course, the repetitive use of toFixed
could also be added to bytesToFloat
instead:
return +f.toFixed(2);
Also, please see How do I format my forum post? and please adjust the comments when you change the code!