Good morning, I am trying to save some data that my arduino is getting and save it into a file, the problem is the processing is not writing into the file, the data is correct and the processing is getting the data perfectly, the only problem is when it has to write into the file. The file is also created perfectly but is empty, here is my processing code:
import processing.serial.Serial;
import java.util.Scanner;
Serial myPort;
PrintWriter myfile;
String arduinoString = "NoValueYet"; // text received from the Arduino
int arduinoInt = 0;
float arduinoFloat = 0.0;
// integer received from the Arduino
final color RED = color(255,0,0), GRAY = color(150), LIGHTGRAY = color(200);
color c = color(0);
int x = 0;
float y;
void setup() {
size(400,400);
printArray(Serial.list()); // print all port names
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
background(LIGHTGRAY);
myfile = createWriter("data1.txt");
}
void draw() {
/* storing data in myfile */
myfile.println(arduinoString);
myfile.println(arduinoInt);
myfile.println(arduinoFloat);
/* visualizing data in the Processing display window */
stroke(c);
y = map(arduinoInt, 0, 1023, 0, height);
line(x, height, x, height-y);
x = x + 1;
if (x >= width) {
x = 0;
background(LIGHTGRAY);
}
delay(100);
}
void serialEvent (Serial myPort) {
String s = myPort.readStringUntil('\n');
if (s != null) {
Scanner scanner = new Scanner(s);
if (scanner.hasNextInt()) {
arduinoInt = scanner.nextInt();
print(arduinoInt); // I added this file to check that the arduinoInt gets the value and it does
myfile.print(arduinoString); // I added this to check if the problem is between serialEvent and draw, but is not, eventhough I add this line here the number is not saved in my file
}
else if (scanner.hasNextFloat()) {
arduinoFloat = scanner.nextFloat();
}
else if (scanner.hasNext("RED") || scanner.hasNext("YELLOW") || scanner.hasNext("GREEN") ) {
arduinoString = scanner.next();
print(arduinoString);
}
scanner.close();
} // end of if-statement with condition (s != null)
}
void keyPressed() {
myfile.flush(); // writes remaining data
myfile.close();
}