Last active
March 22, 2018 18:40
-
-
Save kmicheli/b66877b9f8f52e0a956f7dcd81220974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This P5 sketch is a template for getting started with Serial Communication. | |
The SerialEvent callback is where incoming data is received | |
By Arielle Hein, adapted from ITP Phys Comp Serial Labs | |
Edited March 13 2018 | |
*/ | |
var sensor1; | |
var sensor2; | |
var serial; //variable to hold an instance of the serial port library | |
var portName = '/dev/cu.usbserial-DN03ZQTJ'; //fill in with YOUR port | |
function setup() { | |
createCanvas(400, 400); | |
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 | |
background('violet'); //background in setup to allow for drawing | |
} | |
function draw() { | |
fill(255,255,255); //ellipse color | |
noStroke(); | |
ellipse(sensor1,sensor2, 20, 20); | |
} | |
//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 inString = serial.readLine(); | |
if(inString.length > 0){ | |
var splitString = split(inString, ','); | |
sensor1 = Number(splitString[0]); | |
sensor2 = Number(splitString[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]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment