TouchDesigner 傳送資料到 Arduino 教學|實現 Serial 通訊控制硬體裝置

本篇教學將引導您如何從 TouchDesigner 傳送資料到 Arduino,透過 Serial (DAT) 和 Python 腳本進行 Serial 通訊,控制燈光、馬達、感測器等實體裝置。包含完整腳本與範例解說,互動設計必學!

Dec 27, 2021
🧰 TouchDesigner 工具庫 | Luxmin Institute on Patreon
我們把接案與展場現場累積下來的 TouchDesigner 元件、專案檔與製作系統,整理發佈在 Patreon,部分工具與 Demo 免費開放下載。
https://www.patreon.com/cw/LuxminInstitute
⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑
這篇教學將引導您如何從 TouchDesigner 傳送資料到 Arduino,實現兩者之間的串列通訊。

TouchDesigner 端

  1. 新增 Serial DAT 運算元
  2. 在 TouchDesigner 中,新增一個 Serial DAT 運算元,用於與 Arduino 進行串列通訊。
    notion image
  3. 設定參數
    • Port:選擇 Arduino 所連接的串列埠。
    • Baud Rate:設定為 9600,與 Arduino 端一致。
    • Row/Callback Format:選擇「One Per Byte」。
  4. 撰寫傳送資料的腳本
  5. 使用 Execute DAT 撰寫以下 Python 腳本,並將其連接到適當的觸發事件(例如按鈕或滑桿):
def onStart(): op('forArduinoOutput').send('n', terminator='\n') return
在此腳本中:
  • forArduinoOutput 是您在第 1 步中建立的 Serial DAT 的名稱。
  • send() 函數用於傳送資料。
  • 'n' 是您要傳送的字串。
  • terminator='\n' 表示在資料末尾添加換行符號,讓 Arduino 能夠識別資料的結尾。
notion image

Arduino 端

  1. 設定串列通訊
  2. 在 Arduino 的 setup() 函數中,初始化串列通訊:
void setup() { Serial.begin(9600); }
  1. 接收並處理資料
  2. 在 loop() 函數中,接收從 TouchDesigner 傳送過來的資料,並根據需要進行處理:
void loop() { String s = ""; while (Serial.available()) { char c = Serial.read(); if (c != '\n') { s += c; } } if (s != "") { if (s == "word") { // 執行相應的操作 } } }
在此程式碼中:
  • 使用 Serial.available() 檢查是否有可讀取的資料。
  • 使用 Serial.read() 讀取資料,並將其組合成一個字串。
  • 當讀取到換行符號 \n 時,表示一筆完整的資料已接收完畢。
  • 如果接收到的字串為 "word",則執行相應的操作。
透過上述步驟,您可以實現從 TouchDesigner 傳送資料到 Arduino,進而控制各種硬體裝置。
⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑⭑
Luxmin Institute (互動研究院) on Patreon
教學講的是觀念,工具則是我們在真實展場裡跑過、改過、確定能用的東西。TD 元件、專案檔、校正與製作流程都陸續發佈在 Patreon 上,免費層可以先看 Demo 與公開工具,付費層取得完整檔案與更新:
https://www.patreon.com/cw/LuxminInstitute
最新的活動動態與報名資訊:
https://www.threads.com/@luxmin.institute
 
如有相關專案或其他需求,請洽 luxmin.art