這是一篇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
2
3
4
5
6
7
8
9
10
1. int AnRead = 0;       // set pin 0 to read the value of variable resistor
3. void setup()
4. {
5. Serial.begin(9600); // Start Serial Port, set baud rate as 9600
6. }
7. void loop()
8. {
9. int VariableRes = analogRead(AnRead); //read variable resistor
10. Serial.write(VariableRes/4);
11. delay(100);
  1. }

 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. ellipse(160, 120, VariableRes, 55);
  22. // ellipse(a, b, c, d)
  23. //Parameters
  24. //a  float: x-coordinate of the ellipse
  25. //b  float: y-coordinate of the ellipse
  26. //c  float: width of the ellipse by default
  27. //d  float: height of the ellipse by default
  28. output.println(VariableRes); // Write the coordinate to the file
  29. output.flush(); // Writes the remaining data to the file
  30. }
  31. }

執行結果:

arduino_processing 01.jpg

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

data.txt的內容為:

arduino_processing 02.jpg

參考文章:

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

https://lab.cavedu.com/processing

https://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

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

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