I just started using Processing today and kind of just jumped right into it. I used it a lot on Khan Academy but never with an Arduino. I have a book that taught me a little bit about how to use processing and using it with an Arduino. All of my code works properly except for the enormous amount of lag. I have a joystick and a button that controls a rectangle in the canvas. When I move the joystick, it should instantly move the rectangle accordingly. I wait for a minimum of 40 seconds and the longer my code runs the more lag I experience. Is this something to do with my laptop or Processing? How do I fix it?
Arduino code:
int stickX, stickY, stickBtnState, btnState, stickBtnPin = 4, btnPin = 2, stickXPin = 0, stickYPin = 1;
void setup() {
Serial.begin(9600);
pinMode(btnPin, INPUT);
pinMode(stickBtnPin, INPUT);
}
void loop() {
stickX = analogRead(0) / 4;
stickY = analogRead(1) / 4;
stickBtnState = digitalRead(stickBtnPin);
btnState = digitalRead(btnPin);
Serial.print("X:");
Serial.println(stickX);
Serial.print("Y:");
Serial.println(stickY);
Serial.print("sBtn:");
Serial.println(stickBtnState);
Serial.print("btn:");
Serial.println(btnState);
delay(3);
}
Processing code:
import processing.serial.*;
Serial port;
int x = 10, y = 10;
float stickX, stickY, stickBtn, btn, colour = 0;
String readSerial;
void setup() {
size(400, 400);
port = new Serial(this, Serial.list()[0], 9600);
}
void draw() {
background(255);
fill(colour);
rect(x, y, 10, 10);
serialEvent();
}
void serialEvent() {
String inString = port.readStringUntil('\n');
if (inString != null) {
if (inString.indexOf('X') == 0) {
inString = inString.substring(2);
stickX = float(inString);
println(stickX);
if (stickX > 135) {
x++;
} else if (stickX < 125) {
x--;
}
} else if (inString.indexOf('Y') == 0) {
inString = inString.substring(2);
stickY = float(inString);
if (stickY > 135) {
y++;
} else if (stickY < 125) {
y--;
}
} else if (inString.indexOf('s') == 0) {
inString = inString.substring(5);
stickBtn = float(inString);
if (stickBtn == 1) {
colour = 100;
}
} else if (inString.indexOf('b') == 0) {
inString = inString.substring(4);
btn = float(inString);
if (stickBtn == 1) {
colour = 255;
}
}
}
}
Any help is greatly appreciated by me. Thanks!