import processing.serial.*;
Serial arduinoPort; // Serial port object
int xPos, yPos; //joystick position
int prevX, prevY; //previous joystick position
int swState = 1, btn1State = 1, btn2State = 1;
int prevBtn1State = 1; // To track previous Button 1 state
int prevBtn2State = 1; // To track previous Button 2 state
color drawColor; //color
int sum = 0;
void setup() {
fullScreen();
drawColor = color(0);
println("Initial color: Black");
println(Serial.list()); // Print ports
if (Serial.list().length > 0) {
arduinoPort = new Serial(this, "COM10", 9600);
} else {
println("No serial ports available.");
exit();
}
arduinoPort.bufferUntil('\n'); // Wait for end of data line
stroke(0);
// Initialize positions to the center of the canvas
xPos = prevX = width / 2;
yPos = prevY = height / 2;
}
void draw() {
// Draw a line from the previous position to the current position
stroke(drawColor);
strokeWeight(5);
line(prevX, prevY, xPos, yPos);
// Update the previous position to the current position
prevX = xPos;
prevY = yPos;
// Restart the sketch on joystick press
if (swState == 0) {
background(255);
drawColor = color(0); // Color to black
println("Canvas reset, color reset to black!");
}
}
void serialEvent(Serial port) {
String data = port.readStringUntil('\n'); // Read until newline
if (data != null) {
data = trim(data); // Remove any extra whitespace
println("Raw data: " + data);
String[] values = split(data, ',');
if (values.length == 5) {
try {
// Extract numeric values from strings like "x = 203"
int xValue = int(match(values[0], "\\d+")[0]); // Extract the number from "x = 203"
int yValue = int(match(values[1], "\\d+")[0]); // Extract the number from "y = 809"
swState = int(match(values[2], "\\d+")[0]); // Extract SW state
btn1State = int(match(values[3], "\\d+")[0]); // Extract Button 1 state
btn2State = int(match(values[4], "\\d+")[0]); // Extract Button 2 state
// Map joystick values
xPos = int(map(xValue, 0, 1023, 0, width));
yPos = int(map(yValue, 0, 1023, 0, height));
// Detect button press
if (btn1State == 0 && prevBtn1State == 1) {
sum++;
drawColor = color(random(255), random(255), random(255)); // Random new color
println("Button 1 pressed! New color: " + drawColor);
}
if(sum == 1){
drawColor = color(0);
}
// Save frame on Button 2 press
if (btn2State == 0 && prevBtn2State == 1) {
saveFrame("snapshot-####.png");
println("Frame saved!");
}
prevBtn1State = btn1State;
prevBtn2State = btn2State;
} catch (Exception e) {
println("Error parsing data: " + e.getMessage());
}
} else {
println("Incomplete data received: " + data);
}
}
}