xxxxxxxxxx
110
// From: https://github.com/yining1023/p5-ble-examples-archived/blob/master/p5_sketches/example1/main.js
// More: https://itp.nyu.edu/camp2019/session/55
const myNamePrefix = 'Twiz';
const optionalServiceUUID = 0x1901; // or '00001901-0000-1000-8000-00805f9b34fb';
var IMU_char;
var valueX = 0, valueY = 0, valueZ = 0;
function connect() {
let options = {
filters: [{
optionalServices: [optionalServiceUUID],
namePrefix: myNamePrefix
}]}
console.log('Requesting Bluetooth Device...');
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('Got device', device.name);
return device.gatt.connect();
})
.then(server => {
console.log('Getting Service...');
return server.getPrimaryService(optionalServiceUUID);
})
.then(service => {
console.log('Getting Characteristics...');
// Get all characteristics.
return service.getCharacteristics();
})
.then(characteristic => {
myCharacteristic = characteristic;
return myCharacteristic.startNotifications().then(_ => {
log('> Notifications started');
myCharacteristic.addEventListener('characteristicvaluechanged',
handle_IMU);
});
})
/*
.then(characteristics => {
console.log('Got Characteristics');
IMU_char = characteristics;
IMU_char.startNotifications();
console.log('> Notifications started');
IMU_char.addEventListener('characteristicvaluechanged', handle_IMU);
console.log('addEventListener() ok');
}) */
.catch(error => {
console.log('Argh! ' + error);
});
}
function handle_IMU(event) {
valueX = event.target.value.getUint8(0);
console.log('> X-Axis: ' + valueX);
}
function setup() {
createCanvas(500, 400, WEBGL);
connect();
}
function draw() {
background(250);
normalMaterial();
push();
rotateX(valueX * 0.01);
rotateY(valueY * 0.01);
rotateZ(valueZ * 0.01);
box(100, 100, 100);
pop();
}
/*
function handleNotifications(theData) {
console.log(theData.length);
if(theData.length==12) {
var values = [];
for(var k=0;k<theData.length;k+=2) {
values.push(theData.readInt16BE(k, 2)); // signed int
}
debug('data',
peripheral.advertisement.localName+"\t"+values[0]+
", "+values[1]+
", "+values[2]+
", "+values[3]+
", "+values[4]+
", "+values[5]);
var n = Math.pow(2, 16);
var rad = 0.0174533;
var ax = (values[0] * 4.0)/n;
var ay = (values[1] * 4.0)/n;
var az = (values[2] * 4.0)/n;
ex = rad * (values[3] * 360.0)/n;
ey = rad * (values[4] * 360.0)/n;
ez = rad * (values[5] * 360.0)/n;
console.log(theData);
}
}
*/