• Translating Arduino Code into Javascript

    The first attempt

    /** 'readAccel() reads X,Y,Z accelerometer values'*/
    LSM9DS1.prototype.readAccel=function(){
     var temp=this.xgReadBytes(Regs.OUT_X_L_XL, 6);
     var i;var mm=[0,0,0];
     this.a[0]=this.twos_comp(temp[0],temp[1]­);
     this.a[1]=this.twos_comp(temp[2],temp[3]­);
     this.a[2]=this.twos_comp(temp[4],temp[5]­);
    etc etc
    }
    /** 'xgReadBytes(subAddress,count) read count bytes from gyro/accelerometer at subAddress'*/
    LSM9DS1.prototype.xgReadBytes=function(s­ubAddress,count){
     var dest= new Uint8Array(count);
     var x=this.xgAddress;
     this.i2c.writeTo(x, subAddress|0x80);
     dest=this.i2c.readFrom(x, count);
     return dest;
    };//end xgReadBytes
    
    /** 'prototype.twos_comp(low,high) converts low and high bytes'*/
    LSM9DS1.prototype.twos_comp=function(low­,high){
     var t=(high << 8) | low;
      return(t & 0x8000 ? t - 0x10000 : t);
    };//end twos_comp
    

    But it can be done differently using ArrayBuffer and DataView
    Read the byte stream into an ArrarBuffer, then use a DataView to convert to signed integers, note the littleEndian flag.

    var A=new ArrayBuffer(12);
    A[0]=1;
    A[1]=0;
    A[2]=0xfe;
    A[3]=0xff;
    var B= new Int16Array(A,0,6);
    console.log(A);
    console.log(B);
    console.log("B0= "+B[0]+" B[1]= "+B[1]);
    //var C=dataview.getUint16(byteOffset [, littleEndian])
    var dataview = new DataView(A);
    console.log("A "+dataview.getInt16(0, true)); console.log("A1 "+dataview.getInt16(0, false)); 
    console.log("A2 "+dataview.getInt16(2, true)); console.log("A3 "+dataview.getInt16(2, false)); 
    B[0]=23;B[1]=-23;B[2]=56;B[3]=-56;
    console.log(A);
    console.log(B);
    A[0]=2;A[1]=0;
    A[2]=0xfe;A[3]=0xff;
    console.log(A);
    console.log(B);
    
    

    https://developer.mozilla.org/en-US/docs­/Web/JavaScript/Reference/Global_Objects­/DataView/getUint16
    https://developer.mozilla.org/en-US/docs­/Web/JavaScript/Reference/Global_Objects­/DataView/getInt16>

About