這是一篇Arduino與processing結合的文件,

為什麼要使用這兩個軟體,一是程式撰寫概念相近,二是同是開放軟體與硬體,

可以藉由Arduino與processing的合作,產生low cost的軟硬體整合,

其兩者的溝通,主要是藉由串列傳輸來達成,

在Arduino中要使用Serial.write()傳輸資料,而在Processing中則是使用serial.read()讀取資料,其baud rate要設定一致,然後宣告一個新物件PrintWriter output,

裡用output = createWriter("data.txt")在Processing程式所屬資料夾建立檔案,利用output.println(),與output.flush()將字元儲存成text到檔案中。

 

我們使用一個簡單而實用的範例: 利用Arduino讀取Analog pin0的資料,可在Pin0連接可變電阻,然後將資料傳輸到Processing然後存成text檔。

Arduino code:

  1. int AnRead 0;       // set pin 0 to read the value of variable resistor
  2. void setup()
  3. {
  4.   Serial.begin(9600);  // Start Serial Port, set baud rate as 9600
  5. }
  6. void loop()
  7. {
  8.   int VariableRes analogRead(AnRead);  //read variable resistor
  9.   Serial.write(VariableRes/4);
  10.   delay(100);
  11. }

 Processing code:

  1. import processing.serial.*;
  2. Serial serial;
  3. int VariableRes;
  4. PrintWriter output;
  5. void setup()
  6. {
  7.   //set the size of canvas
  8.   size(320,240);
  9.   serial new Serial(this,"COM4",9600);
  10.   // Create a new file in the sketch directory
  11.   output createWriter("data.txt"); 
  12. }
  13. void draw()
  14. {
  15.   if (serial.available()>0)
  16.   {
  17.     VariableRes serial.read();
  18.     println(VariableRes);
  19.     background(255);
  20.     fill(255,255,0);  //yellow
  21.     
  22.     ellipse(160120VariableRes55);
  23.     // ellipse(a, b, c, d)
  24.     //Parameters  
  25.     //a  float: x-coordinate of the ellipse
  26.     //b  float: y-coordinate of the ellipse
  27.     //c  float: width of the ellipse by default
  28.     //d  float: height of the ellipse by default
  29.     
  30.     output.println(VariableRes); // Write the coordinate to the file
  31.     output.flush(); // Writes the remaining data to the file
  32.     
  33.   }
  34. }

 

執行結果:

arduino_processing 01.jpg

調整可變電阻會改變橢圓的寬度。

data.txt的內容為:

 arduino_processing 02.jpg  

參考文章:

http://playground.arduino.cc/Interfacing/Processing

http://lab.cavedu.com/processing

http://blog.lyhdev.com/2012/04/processing.html

https://zh.m.wikibooks.org/zh-tw/Processing%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97

http://www.makezine.com.tw/make2599131456/processing1youbike

http://coopermaa2nd.blogspot.tw/2011/03/processing-arduino.html

arrow
arrow
    文章標籤
    processing arduino serial port
    全站熱搜

    fishark 發表在 痞客邦 留言(0) 人氣()