纳金网
标题:
Unity3D与Arduino通信
[打印本页]
作者:
may
时间:
2015-9-14 05:37
标题:
Unity3D与Arduino通信
首先需要一个客户端就是Arduino的程序
void setup()
{
Serial.begin(9600);
}
void loop() {
int incomingByte = 0;
if (Serial.available() > 0) {
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
复制代码
用arduino编译器新建一个程序,直接复制进去就可以了,简单解释一下:setup是启动函数,相当于unity的start函数,而loop函数相当于Update函数。
下面是unity的代码:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
using System;
using UnityEngine.UI;
public class SerialPortTest : MonoBehaviour
{
public InputField input;
public void buttonOnClick()
{
sp.Write(input.text);
}
//Setup parameters to connect to Arduino
public static SerialPort sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
public string message;
// Use this for initialization
void Start()
{
OpenConnection();
Loom.RunAsync(Read); //Loom.cs可在网上搜搜
}
void Update()
{
}
//Function connecting to Arduino
public void OpenConnection()
{
if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
message = "Closing port, because it was already open!";
}
else
{
sp.ReadTimeout = 500; // sets the timeout value before reporting error
sp.Open(); // opens the connection
message = "Port Opened!";
}
}
else
{
if (sp.IsOpen)
{
print("Port is already open");
}
else
{
print("Port == null");
}
}
}
public static void Read()
{
while (true)
{
try
{
string message = sp.ReadLine();
Loom.EnqueueToMainThread(() => { Debug.Log(message); });
}
catch (TimeoutException) { }
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
复制代码
*注意:BuildSetting里面,API Compatibility Level要修改为.NET2.0,不然无法使用System.IO.Ports;
作者:
XZ_0920
时间:
2015-11-27 17:10
你也玩Arduino?
欢迎光临 纳金网 (http://rs.narkii.com/club/)
Powered by Discuz! X2.5