xxxxxxxxxx
61
/* In P5.js, 9600 bits per second is the default,
so you don’t have to set the rate if you want 9600bps*/
// change the data rate to whatever you wish
// var options = { baudrate: 9600};
var serial; // variable to hold an instance of the serialport library
var portName = '/dev/cu.usbmodem1451'; // fill in your serial port name here
var inData; // for incoming serial data
var xPos = 0; // x position of the graph
function setup() {
createCanvas(400, 300);
serial = new p5.SerialPort(); // make a new instance of the serialport library
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
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialEvent() {
var inString = serial.readLine(); //receiving data as a string value (0-1023);
if (inString.length > 0 ){ // check to see that there's actually a string there
inData = Number(inString); // convert it to a number
}
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}
function draw() {
background(0);
drawDots(inData);
}
function drawDots(newData) {
fill(255);
noStroke();
// map the range of the input to number of dots :
var num = map(newData, 0, 1023, 500, 0);
// draw the dots:
for(i=0;i<num;i++){
ellipse(random(0,width),random(0,height),10,10);
}
}