xxxxxxxxxx
438
/*
> Everything works so far
> The origin has been moved to the middle of the canvas
> Radius has been mapped to a new scale of (100mm == 10 cm) [Measured in Pixels]
> Buttons have been added
[ORDER CHANGED] -- Line number will differ
* For use (with Arduino), uncomment following lines:
1. From Line 59 to 83 (inclusive) [Inside Setup Function]
2. Lines 247 and 248 [send_data_button() function]
3. Everything below 282 (inclusive) [everything below makePortButton() function]
Moved data sending to draw()
--> added new boolean variable called "startSending"
*/
// Global Variables
let canvas_w = 800;
let canvas_h = 800;
let positions = []; // List of points in Cartesian coordinates
let mappedPositions = []; // List of points in Polar coordinates ---- (radius, angle) -----
let isClicked = false;
let errorHandler = -2 * canvas_w;
// 1 cm = 37.795275591 px
// 100 mm = 377.95275591 px
let disc_radius = 600;
let one_px_mm = 0.2645833333;
// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
// HTML button object:
let portButton;
let outByte = 0; // for outgoing data
let inData; // for incoming data
// Loop variable
let i = 0;
let startSending = false;
let drawingFinished = false;
let firstQuad = false;
let fourthQuad = false;
let fullRotationNum = 0;
let firstAngle = true;
function setup() {
createCanvas(canvas_w, canvas_h);
angleMode(DEGREES);
// ------------------------ UNCOMMENT -------------------------------------------
// check to see if serial is available:
if (!navigator.serial) {
alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
}
// if serial is available, add connect/disconnect listeners:
navigator.serial.addEventListener("connect", portConnect);
navigator.serial.addEventListener("disconnect", portDisconnect);
// check for any ports that are available:
serial.getPorts();
// if there's no port chosen, choose one:
serial.on("noport", makePortButton);
// open whatever port is available:
serial.on("portavailable", openPort);
// handle serial errors:
serial.on("requesterror", portError);
// handle any incoming serial data:
serial.on("data", serialEvent);
serial.on("close", makePortButton);
}
let tmp = 1;
function draw() {
background(155);
//Buttons
send_data_button();
reset_button();
// Translate the origin point to the center of the screen
translate(width / 2, height / 2);
// Make sure the mouse is clicked and cursor position is different
if (isClicked && mouseX !== pmouseX && mouseX !== pmouseY) {
// Create a vector and add it to the list
// let pt = createVector(mouseX, mouseY); // When origin is at the top-left corner
let pt = createVector(mouseX - width / 2, mouseY - height / 2);
positions.push(pt);
// Handle the case when x = 0
if (pt.x == 0) pt.x = 0.01;
// Mapping Cartesian to Polar and appending it in mappedPositions array
let temp_list = [];
temp_list = cartToPolar(pt.x, pt.y);
let pt_mapped = createVector(temp_list[0] * one_px_mm, temp_list[1]);
mappedPositions.push(pt_mapped);
// // Handling the big jump
// let len_ = mappedPositions.length;
// let angle_diff = 200
// let old_val;
// let corr = 40;
// // /*
// for (let j = 0; j < (len_-2); j++)
// {
// // Peak angle at (j+1)
// let k = j+1;
// let l = j+2;
// if ((abs(mappedPositions[k].y - mappedPositions[j].y) > angle_diff) && mappedPositions[k].y > 200 && mappedPositions[k].y < 300)
// {
// print("*****\n");
// // print("j " + mappedPositions[j].y)
// // print("k " + mappedPositions[k].y);
// // print("l " + mappedPositions[l].y + "\n");
// if (mappedPositions[j].y > 600)
// {
// // Increasing/ Decreasing Trend after (j+1)?
// if ((mappedPositions[l].y - mappedPositions[k].y) > 0)
// corr = -1 * corr;
// else
// corr = corr;
// old_val = mappedPositions[k].y;
// mappedPositions[k].y = (old_val + corr);
// print("Pattern");
// }
// }
// }
// // */
print("counter: " + tmp);
// Printing co-ordinates stored in the list(s)
print("Cartesian: x: " + pt.x + " and y: " + pt.y);
print("Polar: r: " + pt_mapped.x + " and Angle: " + pt_mapped.y);
tmp++;
}
// Draw Settings
noFill();
strokeWeight(5);
strokeJoin(ROUND);
// Go through the list of vectors and plot them
beginShape();
for (let i = 0; i < positions.length; i++) {
let pt = positions[i];
curveVertex(pt.x, pt.y);
}
endShape();
// Data Transmission
if (startSending)
// if (startSending) {
if (inData == "0") {
let temp_var =
str(mappedPositions[i].x) + "," + str(mappedPositions[i].y);
let percent = int((i / mappedPositions.length) * 100);
print("[" + percent + "% completed] " + temp_var);
serial.write(String(temp_var));
i += 1;
if (i == mappedPositions.length) {
startSending = false;
drawingFinished = true;
}
inData = "1";
if (i >= 1)
first_point = false;
}
}
if (drawingFinished) {
serial.write(String("E"));
print("completed!");
i = 0;
startSending = false;
drawingFinished = false;
firstQuad = false;
fourthQuad = false;
fullRotationNum = 0;
}
// }
// Function that converts cartesian values to polar values
// Based on x and y, radius and angle are calculated and returned in the form of an array
//Removed bool_ variable.
let tempAngle;
function cartToPolar(x, y) {
let radius, angle;
let old_angle;
let curr_angle;
radius = sqrt(sq(x) + sq(y));
angle = atan(abs(y) / abs(x));
if (x >= 0 && y >= 0) {
angle = angle;
firstQuad = true;
if (fourthQuad) {
fullRotationNum++;
fourthQuad = false;
}
} else if (x <= 0 && y >= 0) {
angle = 180 - angle;
} else if (x <= 0 && y <= 0) {
angle = 180 + angle;
} else if (x >= 0 && y <= 0) {
angle = 360 - angle;
fourthQuad = true;
if (firstQuad) {
fullRotationNum--;
firstQuad = false;
}
}
angle += fullRotationNum * 360;
if(firstAngle){
firstAngle = false;
tempAngle = angle;
}else{
if(tempAngle - angle > 180){
fullRotationNum++;
angle += 360;
}if(tempAngle - angle < -180){
fullRotationNum--;
angle -= 360;
}
tempAngle = angle;
}
let temp_list = [];
temp_list[0] = map(radius, 0, sqrt(2 * sq(width / 2)), 0, disc_radius); // Mapped radius
temp_list[1] = angle;
return temp_list;
}
// Set boolean to true when mouse is clicked
function mousePressed() {
isClicked = true;
}
// Set boolean to false when mouse is released
function mouseReleased() {
isClicked = false;
}
// Button Function
function button(text_, x, y, w, h) {
// Checks if the cursor is within the button or not
let isWithinButton =
mouseX < x + w && mouseX > x && mouseY < y + h && mouseY > y;
// Hover Effect
if (isWithinButton) {
fill(143, 148, 123);
cursor(HAND);
} else {
fill("grey");
cursor(ARROW);
}
// Button Setting
stroke("black");
strokeWeight(2);
rect(x, y, w, h, 5);
// Text inside the button
textFont("Helvetica");
stroke(5);
textSize(25);
fill("white");
text(text_, x + 18, y + 32);
// Return a boolean value
return isWithinButton;
}
let first_point = false;
// Function that sends data to arduino
function send_data_button() {
let x = canvas_w - 210;
let y = canvas_h - 70;
let w = 180;
let h = 50;
// If the cursor is within the button button() function returns 1, else 0;
let sendBool = button("SEND DATA", x, y, w, h);
// Sending the data if the cursor iswithin the button and mouse is clicked
if (sendBool && mouseIsPressed && !first_point) {
serial.write(String("H"));
first_point = true;
startSending = true;
print("Homing Machine...");
// Printing the list
// print(positions.length);
// print(mappedPositions.length);
// for (let z = 0; z < mappedPositions.length; z++)
// {
// print( (z+1) + ". Radius: " + mappedPositions[z].x + " Angle: " + mappedPositions[z].y);
// }
}
}
// Function that resets the canvas
function reset_button() {
let x = 26;
let y = canvas_h - 70;
let w = 125;
let h = 50;
let msg = "null"
// If the cursor is within the button button() function returns 1, else 0;
let resetBool = button("RESET", x, y, w, h);
// Resetting sketch if the cursor iswithin the button and mouse is clicked
if (resetBool && mouseIsPressed) {
positions = [];
mappedPositions = [];
isClicked = false;
serial.write(String("E"));
print("home");
}
}
// ------------------------------- UNCOMMENT -------------------------------------------
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
// create and position a port chooser button:
portButton = createButton("choose port");
portButton.position(10, 10);
// give the port button a mousepressed handler:
portButton.mousePressed(choosePort);
}
// make the port selector window appear:
function choosePort() {
if (portButton) portButton.show();
serial.requestPort();
}
// open the selected port, and make the port
// button invisible:
function openPort() {
// wait for the serial.open promise to return,
// then call the initiateSerial function
serial.open().then(initiateSerial);
// once the port opens, let the user know:
function initiateSerial() {
console.log("port open");
}
// hide the port button once a port is chosen:
if (portButton) portButton.hide();
}
// pop up an alert if there's a port error:
function portError(err) {
alert("Serial port error: " + err);
}
// read any incoming data as a string
// (assumes a newline at the end of it):
function serialEvent() {
inData = Number(serial.read());
}
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
console.log("port connected");
serial.getPorts();
}
// if a port is disconnected:
function portDisconnect() {
serial.close();
console.log("port disconnected");
}
function closePort() {
serial.close();
}