纳金网

标题: Unity3D与Arduino通信 [打印本页]

作者: may    时间: 2015-9-14 05:37
标题: Unity3D与Arduino通信
首先需要一个客户端就是Arduino的程序
  1. void setup()
  2. {
  3.   Serial.begin(9600);
  4. }
  5. void loop() {
  6.   int incomingByte = 0;
  7.   if (Serial.available() > 0) {
  8.     incomingByte = Serial.read();
  9.     Serial.print("I received: ");
  10.     Serial.println(incomingByte, DEC);
  11.   }
  12. }
复制代码
用arduino编译器新建一个程序,直接复制进去就可以了,简单解释一下:setup是启动函数,相当于unity的start函数,而loop函数相当于Update函数。
下面是unity的代码:
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO.Ports;
  4. using System.Threading;
  5. using System;
  6. using UnityEngine.UI;

  7. public class SerialPortTest : MonoBehaviour
  8. {
  9.     public InputField input;
  10.     public void buttonOnClick()
  11.     {
  12.         sp.Write(input.text);
  13.     }
  14.     //Setup parameters to connect to Arduino
  15.     public static SerialPort sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
  16.     public string message;
  17.     // Use this for initialization
  18.     void Start()
  19.     {
  20.         OpenConnection();
  21.         Loom.RunAsync(Read); //Loom.cs可在网上搜搜
  22.     }
  23.     void Update()
  24.     {
  25.     }
  26.     //Function connecting to Arduino
  27.     public void OpenConnection()
  28.     {
  29.         if (sp != null)
  30.         {
  31.             if (sp.IsOpen)
  32.             {
  33.                 sp.Close();
  34.                 message = "Closing port, because it was already open!";
  35.             }
  36.             else
  37.             {
  38.                 sp.ReadTimeout = 500;  // sets the timeout value before reporting error
  39.                 sp.Open();  // opens the connection
  40.                 message = "Port Opened!";
  41.             }
  42.         }
  43.         else
  44.         {
  45.             if (sp.IsOpen)
  46.             {
  47.                 print("Port is already open");
  48.             }
  49.             else
  50.             {
  51.                 print("Port == null");
  52.             }
  53.         }
  54.     }
  55.     public static void Read()
  56.     {
  57.         while (true)
  58.         {
  59.             try
  60.             {
  61.                 string message = sp.ReadLine();
  62.                 Loom.EnqueueToMainThread(() => { Debug.Log(message); });
  63.             }
  64.             catch (TimeoutException) { }
  65.         }
  66.     }
  67.     void OnApplicationQuit()
  68.     {
  69.         sp.Close();
  70.     }
  71. }
复制代码
*注意:BuildSetting里面,API Compatibility Level要修改为.NET2.0,不然无法使用System.IO.Ports;




作者: XZ_0920    时间: 2015-11-27 17:10
你也玩Arduino?




欢迎光临 纳金网 (http://www.narkii.com/club/) Powered by Discuz! X2.5