- 最后登录
- 2019-12-25
- 注册时间
- 2012-8-24
- 阅读权限
- 90
- 积分
- 71088
- 纳金币
- 52336
- 精华
- 343
|
首先需要一个客户端就是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;
|
|