Search code examples
node.jsbleno

Write float value in Node buffer


I am reading sensor data and I need to send these data via bluetooth so I am using noble/bleno library to subscribe data every time the value change. Here I am confusing how to send data as a buffer.

I have data something like value = 24.3756

So I need to write this in buffer:

let buf = new Buffer(2);
buf.writeIntLE(buf);

But when I convert to ArrayBuffer value shows only 24 (not getting after decimal point)

How to send full float value and read as array buffer ?


Solution

  • First of all please read Buffer documentation here.

    Then please don't use deprecated functions. If you need to create a new buffer use Buffer.alloc or Buffer.allocUnsafe. When you're creating buffer ensure that it can hold the data you want to write there. Next please use a suitable method for writing data. You're writing floating point number, then you have to use Buffer.writeFloatBE/Buffer.writeFloatLE. If you do everything I mentioned you'll end up with a correct solution:

    const buffer = Buffer.allocUnsafe(4);
    buffer.writeFloatLE(24.3756);