xxxxxxxxxx
133
/*
//Adaptted from serial stream example by from Andreas Refsgaard.
//https://editor.p5js.org/AndreasRef/sketches/zMEfp6YP
//adapted by j3nsykes to work with webUSB and remove need for p5serial app running.
// needs this arduino code uploaded to work -->
//https://github.com/j3nsykes/creativeML2020/tree/master/PhysicalTeachableMachines/ML5_neuralNet/Arduino/AnalogInput_WebUSB/webUSB_multipleInput_send
*/
// The neural network is the brain
let brain;
var sensorData = 0;
var data = 0; //give initial values.
let sensorValueInt = 0;
let latestData = "waiting for data"; // you'll use this to write incoming data to the canvas
let x = 0.0;
let y = 0.0;
let z = 0.0;
function setup() {
let canvas = createCanvas(256, 256);
// Only when clicking on the canvas
//canvas.mousePressed(addData);
// Create the model
const options = {
inputs: ['x', 'y', 'z'], //if you have more than 3 inputs add them in here.
outputs: ['label'], // TODO: support ['label']
debug: true,
task: 'classification'
}
brain = ml5.neuralNetwork(options);
// Train Model button
select('#train').mousePressed(trainModel);
background(0);
}
// Add a data record
function addData() {
// Get frequency
let label = select('#label').value();
// console.log(x);
// console.log(y);
// console.log(z);
// Add data
brain.addData({
x: x,
y: y,
z: z
}, {
label
});
}
// Train the model
function trainModel() {
// ml5 will normalize data to a range between 0 and 1 for you.
brain.normalizeData();
// Train the model
// Epochs: one cycle through all the training data
brain.train({
epochs: 100
}, finishedTraining);
}
// When the model is trained
function finishedTraining() {
brain.classify([x, y, x], gotResults);
}
// Got a result
function gotResults(error, results) {
if (error) {
console.error(error);
return;
}
// Show classification
select('#classification').html(results[0].label);
// Predict again
brain.classify([x, y, x], gotResults);
}
// There is data available to work with
function gotData() {
// console.log(sensorData);
if (sensorData != 0) { //allow for Serial to start stream at beginning.
sensorData = str(sensorData); //parse to string.
let splitString = splitTokens(sensorData, ';'); //seperate at the ';'
// console.log(splitString);
data = JSON.parse(splitString); //parse to JSON object
// console.log(data);
// console.log(data.tX);
// console.log(data.tY);
// console.log(data.tZ);
//get the individual values
x = float(data.tX);
y = float(data.tY);
z = float(data.tZ);
}
}
function draw() {
//maybe add setinterval to control more?
gotData(); //get the webUSB serial information!!!
if (mouseIsPressed) {
addData();
let label = select('#label').value();
background(0, 255, 0);
text("Adding training data for " + label + ": " + x + "," + y + "," + z, 10, 50);
} else {
background(0);
}
}