As an update to this conversation, I had to make a minor change to the data buffer, changing it from ArrayBuffer to Uint8Array so that I could use buf.set(...) to push the older samples out. I presume that .set is going to be more efficient than anything I could have done programmatically.
So here are the relevant snippets from my working code:
var ELEMENT_SIZE = 10; // 10 bytes per data structure (uint32, 3 x int16)
...
// define various setters and getters (could probably put this in a 'required' module
DataView.prototype.setInt16i = function(v) {
this.setInt16(this.idx,v);
this.idx+=2;
};
DataView.prototype.setUint32i = function(v) {
this.setInt32(this.idx,v);
this.idx+=4;
};
DataView.prototype.getInt16i = function() {
var v = this.getInt16(this.idx);
this.idx+=2;
return v;
};
DataView.prototype.getUint32i = function() {
var v = this.getInt32(this.idx);
this.idx+=4;
return v;
};
DataView.prototype.flush = function() {
this.idx=0;
};
// buffer to store data samples
var buf = new Uint8Array(100*ELEMENT_SIZE); // enough room for 100 samples
var d = new DataView(buf.buffer);
d.flush();
...
// A function to sample and store data into buffer
function log() {
// is the buffer full? If so, push it
if (d.idx >= d.buffer.length-ELEMENT_SIZE) {
// move all history values back by one element
buf.set(new Uint8Array(buf.buffer,ELEMENT_SIZE));
d.idx -= ELEMENT_SIZE;
}
// sample the rest of the data and store it all in buffer
d.setUint32i(Math.floor(Date.now()/1000));
d.setInt16i(Math.floor(NRF.getBattery()*1000));
d.setInt16i(temps[0]);
d.setInt16i(temps[1]);
}
...
// This is a utility function that will output our data
// in a form that can just be copy/pasted into a spreadsheet
function output() {
clearInterval(timer);
var saveIdx = d.idx;
d.flush();
while (d.idx < saveIdx) {
var dt = d.getUint32i();
var bat = d.getInt16i();
var temp1 = d.getInt16i();
var temp2 = d.getInt16i();
var line = [dt,bat/1000,temp1/10,temp2/10].join(",");
console.log(line+"\n");
i++;
}
d.idx = saveIdx;
startSampling();
}
Note that the output() function might look a bit cumbersome, but that's mainly because I want to retain the current data set rather than output and flush the old stuff...
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
As an update to this conversation, I had to make a minor change to the data buffer, changing it from ArrayBuffer to Uint8Array so that I could use buf.set(...) to push the older samples out. I presume that .set is going to be more efficient than anything I could have done programmatically.
So here are the relevant snippets from my working code:
Note that the output() function might look a bit cumbersome, but that's mainly because I want to retain the current data set rather than output and flush the old stuff...
Thanks for everyone's help!
Tom