Processing摸索前行(3)
阿新 • • 發佈:2018-11-27
前面兩篇文章,是初步熟悉一下這個軟體在視覺化功能上的應用,那麼,我們主要想要把他用在實戰中。比如,我們接下來要介紹的Processing與Arduino的互動中。比如在Processing中展示Arduino上傳過來的資料。
一、如何呼叫串列埠並取得通訊
呼叫串列埠的第一步就是要引入串列埠的檔案資源,這個和Java的呼叫方式是一直的,只不過,我們可以通過選單直接來完成:
在程式碼中自動插入:
import processing.serial.*;
這裡,我們首先實現從串列埠獲取資料:
import processing.serial.*; Serial sp; int val; void setup() { size(400,300); line(40,50,200,200); sp=new Serial(this,"com3",9600); } void draw() { while(sp.available()>0) { val=sp.read(); print(val); } }
在Arduino端,我們只要簡單的實現串列埠的傳送即可,具體Arduino的串列埠設定,這裡不贅述,程式碼如下
int val=13;
void setup() {
Serial.begin(9600);
}
void loop() {
delay(200);
Serial.println(val);
//Serial.write(val);
delay(200);
}
以上的程式碼已經實現了最基本的串列埠通訊功能。也僅僅是Processing能夠從Arduino中獲取資料了。下面我們將要對這些資料進行圖形顯示。
二、正確獲取串列埠通訊資料
以下程式完成通過在arduino板的模擬口接入變阻器,通過串列埠傳送變阻器資料到Processing,在Processing中呈現影象的功能。
arduino端
int ledpin=13; int pot=0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(ledpin,OUTPUT); } void loop() { // put your main code here, to run repeatedly: int val; int percent; val=analogRead(pot); percent=map(val,0,680,0,254); Serial.write(percent); }
Processing端
import processing.serial.*;
Serial myport;
int portCount=0;
float val,data;
void setup()
{
size(400,320);
portCount=Serial.list().length;
println();
println("Connecting to ->"+ Serial.list()[portCount-1]);
myport=new Serial(this,Serial.list()[portCount-1],9600);
val=0;
frameRate(10);
}
void draw()
{
while(myport.available()>0)
{
//對應的arduino端使用Serial.println
// String inBuffer = myport.readString();
// if (inBuffer != null) {
// println(inBuffer);
// }
//對應的arduino端使用Serial.write
val=myport.read();
println(val);
fill(204, 102, 0);
rect(10,40,380,250);
if(val>0)
{
rect(10,290,380,val-250);
rect(10,40,380,250-val);
}
}
}
隨著電位器的值變化,Processing圖中的兩條下的距離發生變化,形成開合的圖形效果。執行效果如下:
有關arduino通過串列埠傳送資料,在Processing中的顯示不正確的解決方案,我在下面的文章中已經闡述清楚:
關於arduino通過串列埠傳送到processing的資料混亂(錯誤\顯示不正確)的問題解答
如果您是通過搜尋引起直接閱讀的本章節,可以通過連線來回顧前面的內容:
Processing摸索前行(1)
Processing摸索前行(2)