xxxxxxxxxx
74
let serial; // variable to hold an instance of the serialport library
let portName = '/dev/tty.usbserial-1410'; // fill in your serial port name here
let inData;
let xPos = 0;
function setup() {
createCanvas(300,300);
background(0);
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
serial.open(portName); // open a serial port
}
function draw(){
// background(0);
// fill(255);
// textSize(20);
// text("value: "+inData,100,150);
// ellipse(150,150,inData,inData);
graphData(inData);
}
function graphData(newData) {
// map the range of the input to the window height:
var yPos = map(newData, 0, 255, 0, height);
// draw the line in a pretty color:
stroke(0xA8, 0xD9, 0xA7);
line(xPos, height, xPos, height - yPos);
// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
// clear the screen by resetting the background:
background(0x08, 0x16, 0x40);
} else {
// increment the horizontal position for the next reading:
xPos++;
}
}
function printList(portList) {
for (var i = 0; i < portList.length; i++) {
console.log(i + portList[i]);
}
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialEvent() {
let inString=serial.readLine();
if(inString.length>0){
inData=Number(inString);
}
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}