xxxxxxxxxx
94
// The serviceUuid must match the serviceUuid of the device you would like to connect
const serviceUuid = '00001901-0000-1000-8000-00805f9b34fb';
let myCharacteristic;
let myValue = 0;
let myBLE;
var timestamp;
function setup() {
// Create a p5ble class
myBLE = new p5ble();
createCanvas(200, 200);
textSize(20);
textAlign(CENTER, CENTER);
// Create a 'Connect and Start Notifications' button
const connectButton = createButton('Connect and Start Notifications')
connectButton.mousePressed(connectAndStartNotify);
// Create a 'Stop Notifications' button
const stopButton = createButton('Stop Notifications')
stopButton.mousePressed(stopNotifications);
}
function connectAndStartNotify() {
// 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];
// Start notifications on the first characteristic by passing the characteristic
// And a callback function to handle notifications
myBLE.startNotifications(myCharacteristic, handleNotifications, 'uint16');
// You can also pass in the dataType
// Options: 'unit8', 'uint16', 'uint32', 'int8', 'int16', 'int32', 'float32', 'float64', 'string'
// myBLE.startNotifications(myCharacteristic, handleNotifications, 'string');
}
// A function that will be called once got characteristics
function handleNotifications(data) {
var delta_ms = millis() - timestamp;
console.log('data: ', data.toString(16), 't = ', delta_ms) ;
myValue = data;
}
// A function to stop notifications
function stopNotifications() {
myBLE.stopNotifications(myCharacteristic);
}
function draw() {
background(250);
// Write value on the canvas
text(myValue, 100, 100);
}
/*
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);
}
}
*/