xxxxxxxxxx
87
var serial; //variable to hold an instance of the serial port library
var portName = 'COM3'; //fill in with YOUR port
var pot1 = 0;
var pot2 = 0;
function setup() {
createCanvas(400, 300);
serial = new p5.SerialPort(); //a new instance of serial port library
//set up events for serial communication
serial.on('connected', serverConnected);
serial.on('open', portOpen);
serial.on('data', serialEvent);
serial.on('error', serialError);
serial.on('close', portClose);
//open our serial port
serial.open(portName);
//let's figure out what port we're on - useful for determining your port
// serial.on('list', printList); //set a callback function for the serialport list event
// serial.list(); //list the serial ports
}
function draw() {
background('dodgerblue');
ellipse(width/2, height/2, pot1, pot2);
}
function keyTyped(){
if(key === 'r'){
print('r');
serial.write(10); //i decide 10 = red
} else if(key === 'g'){
print('g');
serial.write(11);
}
return false;
}
//all my callback functions are down here:
//these are useful for giving feedback
function serverConnected(){
console.log('connected to the server');
}
function portOpen(){
console.log('the serial port opened!');
}
//THIS IS WHERE WE RECEIVE DATA!!!!!!
//make sure you're reading data based on how you're sending from arduino
function serialEvent(){
//receive serial data here
var incomingString = serial.readLine();
if(incomingString.length > 0){
var sensorArray = split(incomingString, ",");
pot1 = Number(sensorArray[0]);
pot2 = Number(sensorArray[1]);
}
}
function serialError(err){
console.log('something went wrong with the port. ' + err);
}
function portClose(){
console.log('the port was closed');
}
// 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:
print(i + " " + portList[i]);
}
}