【发布时间】:2018-12-05 18:06:23
【问题描述】:
大约 5 小时前,我被介绍到 Processing 以从我的 Arduino 获取数据。这对我来说似乎很有意义,而且我以前没有 Java 经验,但对 C、C+ 和 Matlab 很熟悉(但仍然很不稳定),所以没有什么出乎意料的。我根据许多其他代码(我比较的一种方法是here (official site) 和here)整理了我的代码,它似乎是正确的。
我的问题是处理创建的文件是空的。此外,该文件是在 Arduino 的数据开始在控制台中显示之前创建的。所以我想知道为什么文件被创建但从未真正改变过?我知道在 Processing 运行时文件可能是空的,但是当我点击停止按钮时,我希望根据 Processing 对 createWriter 的定义(之前链接)会调用 keyPressed。
import processing.serial.*;
// Dynamic constants
String portNum = "COM4"; // Choose COM port -- will vary by computer
String FileName = "test.txt"; // Name will change for data collection
// Static constants
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
PrintWriter output;
void setup() {
//String portName = Serial.list()[portNum];
myPort = new Serial(this, portNum, 9600);
output = createWriter(FileName);
}
void draw() {
if (myPort.available() > 0) { // If data is available,
val = myPort.readStringUntil('\n'); // read it and store it in val
}
if (val != null) { // For valid data
output.println(val); // print data
println(val); // To see it's working
}
}
void keyPressed() {
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}
【问题讨论】:
标签: file-io arduino processing