Serial interface binary communication

Posted on
  • How do you send binary messages that need to be specific in size?

    For example I need to send 0x1 as 16 bits or other such combinations. I suspect sending it as a number would always send over 32bit integers?

    Is there an elegant way to construct messages that consist of bytes/words/ints that you'd individually add together or do I have to build a string out of the values?

    Thanks

  • Hi,

    Serial.write(X) will always write 8 bits for numbers - but if you supply a string or array it'll write each element separately as 8 bits.

    To do it 'nicely', I'd use Typed Arrays. The code would look a bit like:

    var buffer = new ArrayBuffer(16); // 8 bytes
    var i32 = new Int32Array(buffer);
    var i16 = new Int16Array(buffer);
    var i8 = new Int8Array(buffer);
    
    i8[4] = 255; 
    // buffer = [0,0,0,0,255,0,0,0];
    i16[2] = 0x0102; 
    // buffer = [0,0,0,0,2,1,0,0];
    i32[1] = 0x01020304; 
    // buffer = [0,0,0,0,4,3,2,1];
    
    // Finally:
    Serial1.write(buffer);
    

    You don't have to be 'aligned' either. You can do:

    var x32 = new Int32Array(buffer,2 /* 2 bytes offset*/);
    x32[0] = 0x01020304; 
    // buffer = [0,0,4,3,2,1,0,0];
    

    Hope that helps!

  • Thanks, I'll try it out and report :)

  • One more thing,

    when reading data using the .on('data', function(data) {...}), do I need to create a buffer out of the string? Is the data always string? The docs seem to say so

  • I can confirm that the sending works fine and I get responses back :) Thanks again

  • Great, glad it's going!

    when reading data using the .on('data', function(data) {...}), do I need to create a buffer out of the string? Is the data always string? The docs seem to say so

    Yes, the data is always a string. You can use it as-is using data.charCodeAt(..), but if you want to access the binary data as an array, a nice easy way is to use E.toArrayBuffer(string)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Serial interface binary communication

Posted by Avatar for user48681 @user48681

Actions