ตัวอย่างนี้ ต่อมาจาก Serial to graph 2 และใช้คู่กับโปรแกรม Arduno ในตัวอย่าง Serial readd write 1
การทำงาน
Processing ส่งตัวอักษร '1' ออกทางพอร์ทอนุกรม
โปรแกรม
import processing.serial.*;
Serial myPort; // กำหนดตัวแปรสำหรับพอร์ทอนุกรม
float[] vals;
int zero_line;
int lf = 10; // Linefeed in ASCII
String myString = null;
void setup()
{
size(800,1000); // ขนาดหน้าต่างแสดงผล
smooth();
println(Serial.list()); // แสดงพอร์ทที่มีอยู่
myPort = new Serial(this, Serial.list()[1], 9600); // เรียกใช้พอร์ทหมายเลข [1]
vals = new float[width]; // An array for store data, array size = width of windows (400)
zero_line = height + 10; //Location for vals = 0;
for (int i = 0; i < vals.length; i++)
{
vals[i] = 0; //initial value
}
draw_line();
}
void draw()
{
myPort.write('1');
while (myPort.available() > 0) //ตรวจสอบว่ามีข้อมูลใหม่หรือไม่ ถ้ามีรับข้อมูลและเขียนกราฟ
{
background(255);
get_data();
draw_line();
}
}
//-------------------------------------------------------
void get_data()
{
// Slide everything down in the array
for (int i = 0; i < vals.length-1; i++)
{
vals[i] = vals[i+1];
}
myString = myPort.readStringUntil(lf);
if (myString != null)
{
print(myString); // Prints String
vals[vals.length-1]=float(myString); // Converts to float
}
}
//-------------------------------------------------------
void draw_line()
{
// Draw lines connecting all points
for (int i = 0; i < vals.length-1; i++)
{
stroke(0);
strokeWeight(1);
line(i,zero_line -vals[i],i+1,zero_line -vals[i+1]);
}
}