xxxxxxxxxx
103
let serial; // variable to hold an instance of the serialport library
let portName = "COM7"; // fill in your serial port name here
let wind = 0;
let ballobj;
function setup() {
createCanvas(640, 480);
frameRate(60);
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
// construct a ball object
ballobj = new ball();
}
function draw() {
background(255);
wind = map(inputVal, 0, 1023, 0, 6);
}
// get the list of ports:
function printList(portList) {
// portList is an array of serial port names
for (let i = 0; i < portList.length; i++) {
// Display the list the console:
print(i + " " + portList[i]);
}
}
function serverConnected() {
print("connected to server.");
}
function portOpen() {
print("the serial port opened.");
}
function serialEvent() {
// read a string from the serial port
// until you get carriage return and newline:
let inString = serial.readLine();
print(inString);
}
function serialError(err) {
print("Something went wrong with the serial port. " + err);
}
function portClose() {
print("The serial port closed.");
}
class ball {
constructor() {
this.wind = 0;
this.gravity = -5;
this.speed = 0;
this.yPos = height/2;
}
display() {
noFill();
circle(width/2, this.yPos, 50);
}
move() {
if (this.yPos < 430){
this.yPos += this.speed;
this.speed += this.gravity - windPower;
}
}
}
/*
Arduino code
void setup() {
Serial.begin(9600);
while (Serial.available() <= 0) {
Serial.println("0"); // send a starting message
delay(300); // wait 1/3 second
}
}
void loop() {
while (Serial.available() > 0) {
// read the incoming byte:
int inByte = Serial.read();
int WindPower = analogRead(A0);
Serial.println(WindPower);
}
}
*/