xxxxxxxxxx
106
var serial; // variable to hold an instance of the serialport library
var portName = '/dev/tty.usbserial-A103R586'; // fill in your serial port name here
var freshData = false;
var power = 0;
var x = 0;
function setup() {
createCanvas(800, 600);
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
var options = { baudRate: 115200};
serial.open(portName, options); // open a serial port
background(0);
}
function draw() {
// black background, white text:
//background(32);
fill(255);
// // display the incoming serial data as a string:
var xPos = 10, yPos = 10, yStep = 11
noStroke();
text("Power: " + power/10, xPos, yPos+=yStep);
stroke(255, 255, 0);
fill(255,255,0);
line(x, height, x, height-power/16);
x+=1;
if (x>width) {
x=0;
background(0);
}
}
// 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 serialEvent2() {
//Update this to handle a sting of two number separated by a comma
//print("Serial event");
var temp = serial.readLine();
if (temp.length > 0) {
//This code runs when a whole string has arrived
var parts = temp.split(",");
//var parts = split(temp, ',');
if (parts.length == 2) {
//this code only runs if the string splits into two parts
xAccel = parts[0];
yAccel = parts[1];
}
}
}
function serialEvent() {
print(".");
// read a byte from the serial port, convert it to a number:
var inString = serial.readLine();
//print("data");
//check that we got a whole line:
if (inString.length > 0) {
//print(inString);
freshData = true;
//serial.write('x');
//At this point, we've isolated one 'line' of data
var temp = inString.split(",");
//print("Got " + temp.length + " elements");
power = temp[3];
}
}
function keyPressed() {
if (key == 'r') serial.write('r');
else if (key == 'g') serial.write('g');
else serial.write('x');
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}