I have a sensor which can give information about X and Y position movement, and I want to create a simple interface in which a circle on the screen will move in the same direction as I move the sensor. I use Arduino to send position data (float) through serial communication.
However, the code doesn't seem to work well. The circle I create, sometimes it disappears from the screen, and after a while, it shows up again. Besides, the circle seems to "blink" (I mean it appears/disappears in high frequency) all the time. I'm doubted that the problem is about the buffer, but I'm not so sure. Here is the code I use:
PROCESSING CODE
// import libraries
import java.awt.Frame;
import java.awt.BorderLayout;
import processing.serial.*;
// Serial port to connect to
String serialPortName = "COM3";
/* SETTINGS END */
Serial serialPort; // Serial port object
void setup() {
size(900,900);
noStroke();
serialPort = new Serial(this, serialPortName, 9600);
}
byte[] inBuffer = new byte[50]; // holds serial message
void draw() {
background(0);
if (serialPort.available() > 0) {
float[] x= new float[2];
String myString = "";
try {
serialPort.readBytesUntil('\r', inBuffer);
}
catch (Exception e) {
}
myString = new String(inBuffer);
String[] nums = split(myString, ' ');
try {
x[0] = float(nums[0]); //X
x[1] = float(nums[1]); //Y
}
catch (Exception e) {
}
ellipse(x[0]+500, x[1]+500, 70, 70); //+500 to make the circle in the middle of interface
}
}
Serial communication in Arduino:
Serial.print(xf,DEC); //méthode 1
Serial.print(" ");
Serial.print(yf,DEC);
Serial.print('\r');
Please help me to find the root cause of this problem. Thank you so much!!