xxxxxxxxxx
108
var serial;
var portName = '/dev/tty.usbmodem141301';
var inData;
var xPos=0;
let balls = [];
function setup() {
serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
serial.on('connected', serverConnected); // callback for connecting to the server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
createCanvas(400, 400);
// ball1=new Ball(width/2,height/2);
for (let i = 0; i < 20; i++) {
balls[i] = new Ball(random(width), random(height), random(50))
}
}
function draw() {
background(0);
fill("blue")
circle(inData,height/2,50,50);
fill(255);
text("sensor value: " + inData, 30, 30);
for (let i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].bounce();
for (let j = i+1; j < balls.length; j++) {
if (balls[i].collide(balls[j])) {
balls[i].changeCol();
balls[j].changeCol();
}
}
}
}
class Ball {
constructor(tempX, tempY, tempD=50, tempXvel = 1, tempYvel = 2, tempCol = color(255, 255, 255)) {
this.x = tempX;
this.y = tempY;
this.d = tempD;
this.xVel = tempXvel;
this.yVel = tempYvel;
this.col = tempCol;
}
display() {
fill(this.col);
noStroke();
circle(this.x, this.y, this.d);
}
bounce() {
this.x += this.xVel;
this.y += this.yVel;
if (this.x < this.d / 2 || this.x > width - this.d / 2) {
this.xVel *= -1;
}
if (this.y < this.d / 2 || this.y > height - this.d / 2) {
this.yVel *= -1;
}
}
collide(other){
let distance=dist(this.x,this.y,other.x,other.y);
return (distance<this.d);
}
changeCol(){
this.col=color(random(255),random(255),random(255))
}
}
// get the list of ports:
function printList(portList) {
// portList is an array of serial port names
for (var i = 0; i < portList.length; i++) {
// Display the list the console:
console.log(i + " " + portList[i]);
}
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialEvent() {
inData = Number(serial.read());
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}