我不知道这是否会有所帮助。这是我制作的一个串行代码示例,它根据传入的串行数据绘制 2 个条形图。这是一个处理文件,但它应该类似于 Arduino 草图。至少在serialEvent 的意义上。如果您之前没有使用过处理,则 draw 方法类似于循环方法。也许这段代码中有一些东西可以帮助你。
import processing.serial.*;
Serial myPort;
float[] floatArray;
float f1; float f2;
void setup() {
size(400, 400);
// Prints lists of serial ports
println(Serial.list());
// Usually arduino is port [0], but if not then change it here
myPort = new Serial(this, Serial.list()[0], 9600);
// Don't call serialEvent until new line character received
myPort.bufferUntil('\n');
// Creates and array of floating decimal numbers and initializes its length to 2
floatArray = new float[2];
}
void draw() {
// Draws 2 bars to represent incoming data in patriotic fashion
background(0, 0, 255);
fill(255, 0, 0);
rect(0, f1, 100, height);
fill(255);
rect(100, f2, 100, height);
}
void serialEvent(Serial myPort) {
// Reads input until it receives a new line character
String inString = myPort.readStringUntil('\n');
if (inString != null) {
// Removes whitespace before and after string
inString = trim(inString);
// Parses the data on spaces, converts to floats, and puts each number into the array
floatArray = float(split(inString, " "));
// Make sure the array is at least 2 strings long.
if (floatArray.length >= 2) {
// Assign the two numbers to variables so they can be drawn
f1 = floatArray[0];
f2 = floatArray[1];
println(f2);
// You could do the drawing down here in the serialEvent, but it would be choppy
}
}
}