Processing 與 ESP32 程式碼

From Hackteria Wiki
Jump to: navigation, search

Arduino Part

程式碼開始

void setup() {

 // put your setup code here, to run once:
 Serial.begin(115200);

} void loop() {

 // put your main code here, to run repeatedly:
 float sensorValue = analogRead(34);
 Serial.println(sensorValue);
 delay(1000);

}

程式碼結束

Processing Part

程式碼開始

import processing.serial.*;

Serial myPort; float hueValue = 0; // 初始Hue值 int rectHeight = 4; int rectWidth = 500; int rectX = 0; int rectY = 0;

void setup() {

 String[] portList = Serial.list();
 
 // 印出所有串口名稱
 if (portList.length > 0) {
   println("Serial Ports:");
   for (String port : portList) {
     println(port);
   }
 } else {
   println("No Serial Ports detected.");
 }
 
 size(500, 500);
 colorMode(HSB,360, 100, 100); // 將顏色模式設置為HSB,Hue的最大值為10
 String portName = Serial.list()[1];
 myPort = new Serial(this, portName, 115200);
 println("-------- Program Start --------");

}

void draw() {

 // 檢查是否有可讀取的資料
 while (myPort.available() > 0) {
   // 讀取整行Serial訊號
   String data = myPort.readStringUntil('\n');
   
   if (data != null) { 
     // 將數據轉換為浮點數
     float sensorValue = float(data.trim());
     println("Parsed value: " + sensorValue);
     
     // 將sensorValue轉換為Hue值
     hueValue = map(sensorValue, 50, 90, 0, 360);
     
     // 繪製矩形
     fill(hueValue, 55, 85); // 使用Hue值設置填充色
     rect(rectX, rectY, rectWidth, rectHeight);
     
     // 更新矩形位置
     rectY += rectHeight;
     
     // 限制矩形位置不超出畫布
     if (rectY >= height) {
       rectY = 0;
     }
   }
 }

}

程式碼結束