xxxxxxxxxx
109
/*
Make sure you add the p5.serialport.js file
to your project folder and include it in
your index.html.
You'll also need to have the p5.serialControl
app open.
Make sure you only have one program accessing
the Arduino's serial port at a time. For example,
you cannot have the Arduino serial monitor open
while trying to read serial data in p5.
For a full tutorial:
https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-input-to-the-p5-js-ide/
*/
var serial;
var portName = '/dev/cu.usbmodem143101';
/*
These variables must be global so we can update
them in our parseData() function and access
them in our draw() function. I initialize them
with placeholder values until I receive serial
data to update them.
*/
var buttonValue;
//var potValue = 0;
//var lightValue = 255;
function setup() {
createCanvas(400, 400);
serial = new p5.SerialPort();
serial.open(portName);
/*
Whenever data is received, the parseData()
function defined below will run.
*/
serial.on('data', parseData);
}
function draw() {
background(244);
noStroke();
fill(255, 0, 0);
ellipse(200,200,100);
}
function parseData(){
/*
If sending single value between 0-255
using Serial.write() on Arduino
*/
var inData = serial.read();
print(inData);
console.log(inData);
// potValue = inData;
//var inData = serial.readLine();
/*
parseData() will run every time data
is received on p5's serial connection.
serial.readLine() will return empty
strings until p5 receives a carriage return
- Serial.println() in Arduino. The if
statement below filters these out and only
updates our potValue and lightValue variables
when we receive a complete batch of data -
in our case, the two sensor values.
*/
if (inData.length > 0){
/*
Here I'm using the native js version of split.
Below that you can see the p5 version
of split, which is commented out.
*/
var values = inData.split(',');
console.log(values[0]);
// var values = splitTokens(values, ',');
// print(values);
/*
Once we split the received data into
individual values, we still need to convert
them from strings to integers.
*/
// potValue = int(values[0]);
//lightValue = int(values[1]);
// print(potValue + ',' + lightValue);
}
}