xxxxxxxxxx
69
//accelerometer axis xyz draws circle colors RGB
//capacitive sensor draws to rectangle
var serial;
var portName = '/dev/cu.usbmodem1411'; //!!!change to your port
var x, y, z, touch;
function setup() {
createCanvas(400, 400);
//serial communication:
serial = new p5.SerialPort();
serial.on('connected', serverConnected);
serial.on('open', portOpen);
serial.on('data', serialEvent);
serial.on('error', serialError);
serial.on('close', portClose);
serial.list();
serial.open(portName);
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialError(err) {
console.log('Something went wrong with the serial port.' + err);
}
function portClose() {
console.log('The serial port closed.');
}
function serialEvent() {
// read a string from the serial port until you get carriage return and newline:
var inString = serial.readStringUntil('\r\n');
if (inString.length > 0) { //check to see that there's actually a string there:
if (inString !== 'hello') { // if you get hello, ignore it var sensors = split(inString, ",");
var sensors = split(inString, ','); // split the string on the commas
if (sensors.length > 3) {
x = sensors[0];
y = sensors[1];
z = sensors[2];
touch = sensors[3]; //touch state 1 or 0
}
}
serial.write('bye'); // send a byte requesting more serial data
}
}
function draw() {
background(220);
fill(x, 0, 0);
ellipse(width / 3, height / 2, width / 5);
fill(0, y, 0);
ellipse(2 * width / 3, height / 2, width / 5);
fill(0, 0, z);
ellipse(3 * width / 3, height / 2, width / 5);
if (touch == 1) {
rect(width / 2, height / 2, width / 5, width / 5);
}
console.log(touch);
}