layout | nav_order | title |
---|---|---|
real-time-plotting |
70 |
Web Bluetooth Accelerometer Graphing |
- Upload this sketch to your Nano 33 BLE
- Open Serial Monitor (it's is important otherwise the data transfer won't take place)
- Click the "Connect" button and follow the prompt
const serviceUuid = "19b10000-e8f2-537e-4f6c-d104768a1214";
//const serviceUuid = "180f0000-0000-0000-0000-000000000000";
let myCharacteristic;
let myValue = 0;
let myBLE;
var data = [];
var g;
var dataPoints = 100;
//var plotFlag = true;
//Graphing
$(document).ready(function () {
//var data = [];
var t = new Date();
for (var i = dataPoints; i >= 0; i--) {
var x = new Date(t.getTime() - i * 1000);
data.push([x, NaN, NaN, NaN]);
}
g = new Dygraph(document.getElementById("div_g"), data,
{
//color: 'red',
strokeWidth: 2,
//rollPeriod: 10,
drawPoints: true,
//showRoller: true,
valueRange: [-6, 6],
labels: ['Time', 'X', 'Y', 'Z'],
colors: ['#3B3B98', '#ff5e57', '#1dd1a1'],
fillGraph: true,
pointSize: 3,
stepPlot: false,
ylabel: "X, Y, Z"
//pixelsPerLabel: 10,
});
});
function plot(ax, ay, az) {
// if (plotFlag === true){
// g.updateOptions({'file': []});
// var t = new Date();
// for (var i = dataPoints; i >= 0; i--) {
// var x = new Date(t.getTime() - i * 1000);
// data.push([x, NaN, NaN, NaN]);
// }
// g.updateOptions({'file': data});
// plotFlag = false;
// }
//My test
var d = new Date(); // current time
var x = ax;
var y = ay;
var z = az;
data.shift();
// if (dataPoints>0){
// dataPoints-=1;
// data.shift();
// data.push([d, x, y, z]);
// }
// else{
// data.push([d, x, y, z]);
// }
data.push([d, x, y, z]);
g.updateOptions({ 'file': data });
}
// Bluetooth
function setup() {
// Create a p5ble class
myBLE = new p5ble();
createCanvas(300, 200);
textSize(20);
textAlign(CENTER, CENTER);
// Create a 'Connect' button
const connectButton = createButton('Connect')
connectButton.mousePressed(connectToBle);
}
function connectToBle() {
// Connect to a device by passing the service UUID
myBLE.connect(serviceUuid, gotCharacteristics);
}
// A function that will be called once got characteristics
function gotCharacteristics(error, characteristics) {
if (error) console.log('error: ', error);
console.log('characteristics: ', characteristics);
myCharacteristic = characteristics[0];
// Read the value of the first characteristic
myBLE.read(myCharacteristic, 'string', gotValue);
//plot(myCharacteristic);
}
// A function that will be called once got values
function gotValue(error, value) {
if (error) console.log('error: ', error);
console.log('value: ', value);
myValue = value;
var acceleration = myValue.split('|');
console.log('Acceleration: ', acceleration);
plot(parseFloat(acceleration[0]), parseFloat(acceleration[1]), parseFloat(acceleration[2]));
// After getting a value, call p5ble.read() again to get the value again
myBLE.read(myCharacteristic, 'string', gotValue);
}
function draw() {
background(250);
text(myValue, 150, 100);
}