I still don’t know why the above code behave the way it does. But in the meantime I experimented with multi threading (never worked with it until now, but heard it somewhere) and it seems to work:
import processing.serial.*;
String myString = null;
Serial myPort; // The serial port
PImage imgGreen;
PImage imgRed;
PImage wallpaper;
boolean XFflag = false;
boolean jsonFlag = false;
void setup() {
fullScreen();
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.clear();
imgGreen = loadImage("greenEggSmall.png");
imgRed = loadImage("redEggSmall.png");
wallpaper = loadImage("Wallpaper4.jpg");
}
void draw() {
background(wallpaper);
thread("jSonProcessing");
image(XFflag ? imgGreen : imgRed, 1030, 665);
}
void jSonProcessing() {
while (myPort.available() > 0) {
String myString = myPort.readStringUntil('}');
if (myString != null) {
if (myString.startsWith("{")) {
jsonFlag = true;
} else {
jsonFlag = false;
}
if (jsonFlag == true) {
try {
JSONObject json = JSONObject.parse(myString);
String btnXForward = json.getString("XF");
XFflag = btnXForward.equals("1"); //Updates XF field
}
catch (Exception e) {
println("An error occured, while trying to parse the jSon object.");
}
}
}
}
}